C# – 将Excel数据复制到数组的方法

我根据老板的规范写了一些代码。 一个要求是将大量的Excel数据导入到程序中。 我通过将Excel工作表的使用范围复制到剪贴板,然后用它写入数组来完成此操作。 这是使用Interop完成的。 这确实很好,而且它已经被使用了大约4个月的代码没有任何问题。

不过,我写了这段代码,在实习开始时就没有想太多。 我现在正在一个安静的时刻重新访问它,这让我想,有没有更好(更高效,更优雅)的方式呢? 现在回头看,这似乎有点破解。

谢谢。

使用ac#驱动程序,您可以直接读取excel文件,而无需使用interop:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.OleDb; using System.IO; namespace Immo.Areas.Administration.Controllers { public class SomethingSometingExcelClass { public void DoSomethingWithExcel(string filePath) { List<DataTable> worksheets = ImportExcel(filePath); foreach(var item in worksheets){ foreach (DataRow row in item.Rows) { //add to array } } } /// <summary> /// Imports Data from Microsoft Excel File. /// </summary> /// <param name="FileName">Filename from which data need to import</param> /// <returns>List of DataTables, based on the number of sheets</returns> private List<DataTable> ImportExcel(string FileName) { List<DataTable> _dataTables = new List<DataTable>(); string _ConnectionString = string.Empty; string _Extension = Path.GetExtension(FileName); //Checking for the extentions, if XLS connect using Jet OleDB if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase)) { _ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0"; } //Use ACE OleDb else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase)) { _ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0"; } DataTable dataTable = null; using (OleDbConnection oleDbConnection = new OleDbConnection(string.Format(_ConnectionString, FileName))) { oleDbConnection.Open(); //Getting the meta data information. //This DataTable will return the details of Sheets in the Excel File. DataTable dbSchema = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables_Info, null); foreach (DataRow item in dbSchema.Rows) { //reading data from excel to Data Table using (OleDbCommand oleDbCommand = new OleDbCommand()) { oleDbCommand.Connection = oleDbConnection; oleDbCommand.CommandText = string.Format("SELECT * FROM [{0}]", item["TABLE_NAME"].ToString()); using (OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter()) { oleDbDataAdapter.SelectCommand = oleDbCommand; dataTable = new DataTable(item["TABLE_NAME"].ToString()); oleDbDataAdapter.Fill(dataTable); _dataTables.Add(dataTable); } } } } return _dataTables; } } } 

是的,这绝对是一个黑客。 如果您使用interop来获取使用的范围,则可以直接遍历该范围并写入数组,而无需任何剪贴板交互。

沿着这些线路的东西:

 for(int i = 1; i <= sheet.UsedRange.Rows.Count; i++) { for(int j = 1; j <= sheet.UsedRange.Columns.Count; j++) { DoStuffWith(sheet.UsedRange.Cells(i, j).Value) } } 

这是一个黑客好吧。

我已经成功地使用了Jet连接( http://connectionstrings.com/excel )。

另一个select是将您的Excel电子表格保存为CSV格式并自己阅读文件。 这可能不实际取决于您的电子表格中的内容。