.NET中使用OleDb读取Excel

在.NET中可以用OleDb(Object linking and embeding DataBase)来访问Excel

 1 using System;

 2 using System.Data;

 3 using System.Windows.Forms;

 4 using System.Data.OleDb;

 5 

 6 namespace ExcelDemo

 7 {

 8     public partial class Form1 : Form

 9     {

10         public Form1()

11         {

12             InitializeComponent();

13         }

14 

15         private void button1_Click(object sender, EventArgs e)

16         {

17             //xls为Excel2003-2007版本的Excel文件后缀,而xlsx为2007以上版本的后缀名

18             //var dt = ExcelToDataTable(@"E:\WorkSpace\VS\ExcelDemo\test.xls", "sheet1");

19             var dt = ExcelToDataTable(@"E:\WorkSpace\VS\ExcelDemo\test.xlsx", "sheet1");

20             this.dataGridView1.DataSource=dt;

21         }

22         private DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)

23         {

24             //Jet和Ace都是连接Excel对象的接口引擎,但是二者有区别.

25             //string strConn = "Provider=Microsoft.Jet.OLEDB.8.0;" + "Data Source=" + strExcelFileName + ";" + 

26             //"Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";

27             string strConn = @"Provider=Microsoft.Ace.OLEDB.12.0;" + "Data Source=" + strExcelFileName + ";" + 

28                 "Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';";

29             string strExcel = string.Format("select * from [{0}$]", strSheetName);

30             //创建OleDb连接,对于特定的数据源类型,传入不同的连接字符串

31             OleDbConnection connection = new OleDbConnection(strConn);

32             connection.Open();

33             OleDbDataAdapter da = new OleDbDataAdapter(strExcel,connection);

34             var ds = new DataSet();

35             da.Fill(ds,strSheetName);

36             return ds.Tables[strSheetName];

37         }

38     }

39 }

 

最开始用的Excel对象接口引擎为Jet,但是在测试时发现对于Excel2013版本的文件,在执行到31行时会报错"外部表不是标准格式".将Excel另存为2003-2007版本时不报错.

原来Jet引擎和Ace引擎是有区别的,具体参考 http://blog.csdn.net/xifeijian/article/details/8333396

 

你可能感兴趣的:(Excel)