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

 using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb; namespace ExcelDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
//xls为Excel2003-2007版本的Excel文件后缀,而xlsx为2007以上版本的后缀名
//var dt = ExcelToDataTable(@"E:\WorkSpace\VS\ExcelDemo\test.xls", "sheet1");
var dt = ExcelToDataTable(@"E:\WorkSpace\VS\ExcelDemo\test.xlsx", "sheet1");
this.dataGridView1.DataSource=dt;
}
private DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
{
//Jet和Ace都是连接Excel对象的接口引擎,但是二者有区别.
//string strConn = "Provider=Microsoft.Jet.OLEDB.8.0;" + "Data Source=" + strExcelFileName + ";" +
//"Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";
string strConn = @"Provider=Microsoft.Ace.OLEDB.12.0;" + "Data Source=" + strExcelFileName + ";" +
"Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';";
string strExcel = string.Format("select * from [{0}$]", strSheetName);
//创建OleDb连接,对于特定的数据源类型,传入不同的连接字符串
OleDbConnection connection = new OleDbConnection(strConn);
connection.Open();
OleDbDataAdapter da = new OleDbDataAdapter(strExcel,connection);
var ds = new DataSet();
da.Fill(ds,strSheetName);
return ds.Tables[strSheetName];
}
}
}

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

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

05-14 07:10