C# 通过C windows应用程序从Excel 2016读取数据

C# 通过C windows应用程序从Excel 2016读取数据,c#,excel,C#,Excel,我正在开发一个应用程序,我想通过C windows应用程序阅读excel 2016。我编写的代码在excel文件打开时可以正常工作。但是,当我在excel文件未打开时运行代码时,它会抛出一个OLEDBEException外部表不是预期的格式 using System.Data.OleDb; using System; namespace ExcelRead { class Program { static void Main(string[] args) {

我正在开发一个应用程序,我想通过C windows应用程序阅读excel 2016。我编写的代码在excel文件打开时可以正常工作。但是,当我在excel文件未打开时运行代码时,它会抛出一个OLEDBEException外部表不是预期的格式

using System.Data.OleDb;
using System;

namespace ExcelRead
{
 class Program
 {
    static void Main(string[] args)
    {
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\Practice.xlsx';Extended Properties='Excel 8.0;HDR=Yes;'");
        con.Open();
        OleDbCommand cmd = new OleDbCommand("select * from [sheet1$];", con);
        OleDbDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            Console.WriteLine(dr.GetString(0) + "\t" + dr.GetString(1) + "\t" + dr.GetString(2));
        }
        Console.ReadKey();
    }
  }
}

请使用下面的代码,因为您并没有维护可以作为excel工作表的实例生成的连接,这就是为什么会出现错误的原因

    static void Main(string[] args)
    {
            // Create Connection to Excel Workbook
            using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\Practice.xlsx';Extended Properties='Excel 8.0;HDR=Yes;'"))
            {
                OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
                connection.Open();
                // Create DbDataReader to Data Worksheet
                using (OleDbDataReader dr = command.ExecuteReader())
                {
                    Console.WriteLine(dr.GetString(0) + "\t" + dr.GetString(1) + "\t" + dr.GetString(2));
                }
            }
        Console.ReadKey();
    }

它仍然抛出相同的异常。@Ashis,请在连接字符串中使用IMEX=1。