使用C sharp操作Excel电子表格

时间:2011-09-22 12:17:49

标签: c# excel

我需要在C sharp .net 2010中操作Excel Spreadsheets。我需要做的总和是循环遍历Excel电子表格,根据其他电子表格中的一些计算在原始列的左侧添加三列加上一些其他功能。最新最好的方法是什么?目前我正在打开excel电子表格并读取我需要的记录并使用此功能将它们打印到屏幕上:

    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工具处理此问题的建议吗?谢谢你的帮助。

3 个答案:

答案 0 :(得分:3)

您还可以使用OpenXML Framework来操作基于XML的Office文档。我认为,当您确定您的客户只有Office 2007或2010时,最好使用此方法。

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

第三种方法,你的,正在运作,但我认为这在简单的场景中是切实可行的。

答案 1 :(得分:1)

使用Office安装,选择安装Interop库。完成此操作后,转到Add Reference,点击COM标签,然后添加Microsoft Excel 12.0 Objects library

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

然后,您应该在MSDN上阅读this one等教程。

答案 2 :(得分:0)

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