如何在不使用Microsoft.Office.Interop.Excel库的情况下读取C#中的excel文件

我在C#中有一个.Net-Windows应用程序。 我需要打开一个excel并处理它。 我怎样才能做到这一点,而不使用Microsoft.Office.Interop.Excel库?

var fileName = @"C:\ExcelFile.xlsx"; var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ; using (var conn = new OleDbConnection(connectionString)) { conn.Open(); var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); using (var cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] "; var adapter = new OleDbDataAdapter(cmd); var ds = new DataSet(); adapter.Fill(ds); } } 

我强烈推荐使用CSharpJExcel来读取Excel 97-2003文件(xls)和ExcelPackage来读取Excel 2007/2010文件(Office Open XML格式,xlsx)。

他们都完美的工作。 他们完全不依赖任何东西。

使用CSharpJExcel的示例:

 Workbook workbook = Workbook.getWorkbook(new System.IO.FileInfo(fileName)); var sheet = workbook.getSheet(0); ... var content = sheet.getCell(colIndex, rowIndex).getContents(); ... workbook.close(); 

使用ExcelPackage的示例:

 using (ExcelPackage xlPackage = new ExcelPackage(existingFile)) { // get the first worksheet in the workbook ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1]; int iCol = 2; // the column to read // output the data in column 2 for (int iRow = 1; iRow < 6; iRow++) Console.WriteLine("Cell({0},{1}).Value={2}", iRow, iCol, worksheet.Cell(iRow, iCol).Value); // output the formula in row 6 Console.WriteLine("Cell({0},{1}).Formula={2}", 6, iCol, worksheet.Cell(6, iCol).Formula); } // the using statement calls Dispose() which closes the package. 

编辑

还有另一个项目, ExcelDataReader ,似乎有能力处理这两种格式。 像我提到的其他人一样容易。

还有其他的图书馆:

  • NPOI:Apache POI库到.NET的端口 :
    非常强大,免费,开源。 除Excel(97-2010)外,它还支持Word和PowerPoint文件。

  • ExcelLibrary :
    它只支持Excel 97-2003(xls)文件。

  • EPPlus :
    ExcelPackage的扩展。 更容易使用(我猜)。

我会敦促使用OleDB,特别是如果它将在服务器上运行。 从长远来看,它可能会让你付出更多的代价 – 例如,我们有一个SSIS工作,调用一个存储过程,OleDB读取sptroc中的excel文件,并使SQL框崩溃! 我把OleDB的东西拿出来,停止了服务器的崩溃。

我发现的一个更好的方法是使用Office 2003和XML文件来完成 – 关于服务器端Office自动化的注意事项 。 注意:Office 2003是这个飞行的最低要求:

参考阅读从Excel: http : //www.roelvanlisdonk.nl/? p= 924 (请做更多的研究,以find其他的例子)

编写Excel电子表格参考 : http : //weblogs.asp.net/jgaylord/archive/2008/08/11/use-linq-to-xml-to-generate-excel-documents.aspx

 public void ReadExcelCellTest() { XDocument document = XDocument.Load(@"C:\BDATA\Cars.xml"); XNamespace workbookNameSpace = @"urn:schemas-microsoft-com:office:spreadsheet"; // Get worksheet var query = from w in document.Elements(workbookNameSpace + "Workbook").Elements(workbookNameSpace + "Worksheet") where w.Attribute(workbookNameSpace + "Name").Value.Equals("Settings") select w; List<XElement> foundWoksheets = query.ToList<XElement>(); if (foundWoksheets.Count() <= 0) { throw new ApplicationException("Worksheet Settings could not be found"); } XElement worksheet = query.ToList<XElement>()[0]; // Get the row for "Seat" query = from d in worksheet.Elements(workbookNameSpace + "Table").Elements(workbookNameSpace + "Row").Elements(workbookNameSpace + "Cell").Elements(workbookNameSpace + "Data") where d.Value.Equals("Seat") select d; List<XElement> foundData = query.ToList<XElement>(); if (foundData.Count() <= 0) { throw new ApplicationException("Row 'Seat' could not be found"); } XElement row = query.ToList<XElement>()[0].Parent.Parent; // Get value cell of Etl_SPIImportLocation_ImportPath setting XElement cell = row.Elements().ToList<XElement>()[1]; // Get the value "Leon" string cellValue = cell.Elements(workbookNameSpace + "Data").ToList<XElement>()[0].Value; Console.WriteLine(cellValue); } 

我最近发现这个库将Excel工作簿文件转换成数据集 : Excel数据读取器

如果您需要打开XLS文件而不是XLSX文件, http://npoi.codeplex.com/是一个不错的select。; 我们已经用它来对我们的项目产生良好的影响。

寻找GSpread.NET。 这也是一个OpenSource项目,它不需要安装Office。 您可以使用Microsoft Excel中的API处理Google电子表格。 如果您想重新使用旧代码来访问Google Spreadsheets,那么GSpread.NET是最好的方法。 你需要添加几行:

 Set objExcel = CreateObject("GSpreadCOM.Application") // Name - User name, any you like // ClientIdAndSecret - `client_id|client_secret` format // ScriptId - Google Apps script ID app.MailLogon(Name, ClientIdAndSecret, ScriptId); 

其他代码保持不变。

http://scand.com/products/gspread/index.html

您可以尝试OleDB从Excel文件中读取数据。 请尝试如下…

 DataSet ds_Data = new DataSet(); OleDbConnection oleCon = new OleDbConnection(); string strExcelFile = @"C:\Test.xlsx"; oleCon.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelFile + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";; string SpreadSheetName = ""; OleDbDataAdapter Adapter = new OleDbDataAdapter(); OleDbConnection conn = new OleDbConnection(sConnectionString); string strQuery; conn.Open(); int workSheetNumber = 0; DataTable ExcelSheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); SpreadSheetName = ExcelSheets.Rows[workSheetNumber]["TABLE_NAME"].ToString(); strQuery = "select * from [" + SpreadSheetName + "] "; OleDbCommand cmd = new OleDbCommand(strQuery, conn); Adapter.SelectCommand = cmd; DataSet dsExcel = new DataSet(); Adapter.Fill(dsExcel); conn.Close(); 

我已经使用了Excel.dll库,它是:

  • 开源
  • 轻量级
  • 快速
  • 与xls和xlsx兼容

这里可用的文档: https : //exceldatareader.codeplex.com/

强烈推荐。

如果你不想使用互操作,你可能想尝试OfficeWriter 。 这取决于你真正需要在文件上做多less处理,但这可能是过度的。 您可以申请免费试用。 在文档站点有一个完整的文档api。

免责声明:我是build立最新版本的工程师之一。

你也可以做我所做的事情,并通过像这样的商业控制: http : //www.syncfusion.com/products/reporting-edition/xlsio

在结束商业解决scheme之前,我一直在努力工作多年。 我首先尝试了在我的开发环境中很容易使用的OLEDB方法,但是可以成为部署的武士。 然后我尝试了开源解决scheme,但是大部分已经过时,并且支持不好。

来自syncfusion的xlsio控件只是我使用的,而且很满意,但其他的存在。 如果你能适应它,不要犹豫,这是最好的解决scheme。 为什么? 因为它与系统没有依赖关系,并且支持所有版本的Office。 除了其他优点之外,它的速度非常快。

不,我不为混合工作;)

我刚刚search解决scheme,并遇到Spreadsheetlight

这看起来很有希望。 其开放源代码,可作为nuget包使用。