2017-04-11 1249 views
0

我正在研究一个应用程序,我想通过C#windows应用程序从excel 2016中读取数据。我写的代码(见下面代码)在excel文件打开时工作正常。但是,当我在Excel文件未打开时运行代码时,它会抛出OleDbexception“外部表格未处于预期格式。”通过C#windows应用程序从Excel 2016中读取数据

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(); 
    } 
    } 
} 

回答

0

请使用下面的代码,因为你不保持连接,可产生的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(); 
    } 
+0

它仍然抛出相同的异常。 –

+0

@Ashis,请在连接字符串中使用“IMEX = 1”。 –

相关问题