如何在C#中访问Excel数据

我正在尝试从C#中的Excel中访问数据。 理想情况下,我想把数据放入一个列表或一个系列集合中。 我正在使用这个教程 – http://www.aspsnippets.com/Articles/Read-Excel-file-using-OLEDB-Data-Provider-in-C-Net.aspx 。

这是非常有用的,但我想他错过了数据适配器的一部分。 这里是他的例子后面的代码。

string connectionString = null; connectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = P:\\Visual Studio 2012\\Projects\\SmartSheetAPI\\SmartSheetAPI\\bin\\Debug\\OUTPUT.xls; Extended Properties = 'excel 12.0 Xml; HDR=YES; IMEX=1;';"; //Establish Connection string dataSource = "P:\\Visual Studio 2012\\Projects\\SmartSheetAPI\\SmartSheetAPI\\bin\\Debug\\OUTPUT.xls;"; string excelConnection = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source = " + dataSource + " Extended Properties='Excel 8.0; HDR=Yes'"; OleDbConnection connExcel = new OleDbConnection(connectionString); OleDbCommand cmdExcel = new OleDbCommand(); cmdExcel.Connection = connExcel; //Accessing Sheets connExcel.Open(); DataTable dtExcelSchema; dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); connExcel.Close(); //access excel Sheets (tables in database) DataSet dataset = new DataSet(); string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString(); cmdExcel.CommandText = "SELECT * From [" + SheetName + "]"; da.SelectCommand = cmdExcel; da.Fill(dataset); connExcel.Close(); 

如果你看下面三行你会注意到他使用了da.SelectCommand和da.Fill来填充数据集。 但是我认为这需要一个数据适配器,他没有这个例子。 我曾尝试创build一个数据适配器,如下所示:

 SqlDataAdapter dataadapter = new SqlDataAdapter(); 

但是我得到一个错误,指出:不能隐式地将types'System.Data.OleDb.OleDbCommand'转换为System.Data.SqlClient.SqlCommand'。

我知道这是正确的select语句。 有人可以帮助我我基本上只是想能够访问我在select声明中获得的信息。

你需要一个OleDBDataAdapter ,而不是SqlDataAdapter 。 所以,这样做:

 OleDBDataAdapter da = new OleDBDataAdapter(cmdExcel); da.Fill(dataset); 

Excel是一个OLEDB数据源,因此您应该使用的类将以OleDb为前缀,就像数据库连接的一样,操作以Sql为前缀。

文档

使用Oledb连接访问excel数据总是令人头痛。你可以尝试第三方控件,比如Aspose.Usage非常简单。添加控件引用到你的项目后,你可以尝试下面的代码。

 //Creating a file stream containing the Excel file to be opened FileStream fstream = new FileStream("C:\\book1.xls", FileMode.Open); //Instantiating a Workbook object //Opening the Excel file through the file stream Workbook workbook = new Workbook(fstream); //Accessing the first worksheet in the Excel file Worksheet worksheet = workbook.Worksheets[0]; //Exporting the contents of 7 rows and 2 columns starting from 1st cell to DataTable DataTable dataTable = worksheet.Cells.ExportDataTable(0, 0, 7, 2, true); //Binding the DataTable with DataGrid dataGrid1.DataSource = dataTable; //Closing the file stream to free all resources fstream.Close();