使用C sharp操作Excel Spreadsheats

我需要在C sharp .net 2010中操作Excel Spreadsheets。我需要做的总和是通过一个Excel电子表格循环,根据其他电子表格中的一些计算结果,在原始列的左边添加三列function。 什么是最新和最好的方式来做到这一点? 目前,我正在打开Excel电子表格,并阅读我需要的logging,并将其打印成功:

public static void parseData(string excelFileName) { try { //Workbook workBook = _excelApp.Workbooks.Open(excelFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //Worksheet wkSheet = (Worksheet)_excelApp.Worksheets[1]; //OLEObject oleObject = wkSheet.OLEObjects(Type.Missing); using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\"")) { connection.Open(); OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", connection); OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(); objAdapter1.SelectCommand = objCmdSelect; objAdapter1.Fill(ds); } foreach (System.Data.DataTable myTable in ds.Tables) { //xmlResultSet.Append("<TemplateData>"); foreach (DataRow myRow in myTable.Rows) { //Console.WriteLine("Ca0mon, please work :{0}", myRow); Console.WriteLine("This thing better Work-- MRN: {0}| Patient Name: {1}| Address: {2}| CSSV: {3}", myRow[0], myRow[1], myRow[2], myRow[3]); } } } catch(Exception ex) { } } 

任何关于如何用最新最好的.net工具来解决这个问题的build议? 谢谢你的帮助。

安装Office后,请select安装Interop库。 完成后,请转到Add Reference ,单击COM选项卡,并添加Microsoft Excel 12.0 Objects library

使用using Microsoft.Office.Interop.Excel;命名空间using Microsoft.Office.Interop.Excel;

然后你应该阅读MSDN上的这个教程。

您还可以使用OpenXML框架来处理基于XML的Office文档。 我认为,如果您确信您的客户只有Office 2007或2010,最好使用这种方法。

通过使用Microsoft.Office.Interop.Excel的方法是危险的,因为您只将您的代码链接到您的办公室版本。 最好使用LateBinding编写代码并支持多个Office版本。

你的第三种方法正在工作,但我认为在简单情况下这是可行的。

您可以使用开放源码库,如NPOI https://npoi.codeplex.com/或付费产品,如Aspose.Cells,Syncfusion Excel库,Softartisan Excel库等。这些库的优点是,你不需要MS安装在服务器上的Office。