C#对Excel的调用

来源:互联网 发布:手写字体软件下载 编辑:程序博客网 时间:2024/05/01 17:31

添加引用com中的Microsoft Excel 11.0 Object Library

       程序中添加:using Microsoft.Office.Interop.Excel;

先定义一下:

     Microsoft.Office.Interop.Excel.Application excelApp;
            Microsoft.Office.Interop.Excel.Workbook excelBook;
            Microsoft.Office.Interop.Excel.Worksheet excelSheet;
            try
            {
                //Start Excel and get Application object.
                excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                excelApp.Visible = true;

          //Get a new workbook.
                excelBook = excelApp.Workbooks.Add(Type.Missing);
                excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelBook.ActiveSheet;
                 //以下添加下面的程序
                 .....
            }
            catch (Exception theException)
            {
                String errorMessage;
                errorMessage = "Error: ";
                errorMessage = String.Concat(errorMessage, theException.Message);
                errorMessage = String.Concat(errorMessage, " Line: ");
                errorMessage = String.Concat(errorMessage, theException.Source);

                MessageBox.Show(errorMessage, "Error");
            }
            ------------------------------------------------------------------------------------------------------------------

1、让我们看看在网上流传最多的解决方案:

        public void DataTableToExcel(DataTable dt)        {                       for (int i = 0; i <dt.Rows.Count; i++)            {                for (int j=0;j<dt.Columns.Count;j++)        {                     excelSheet.Cells[i+1,j+1] = dt.Rows[i][j].ToString();                }             }    }不可否认这段程序会不出错误的运行,但是效率就比较低了,会随着数据行和列的增加而增加,主要的时间都耗在了Excel单元格的读取上。

让我们改进一下,利用DataRow.ItemArray:

public void DataTableToExcel(DataTable dt)

{      

int colCount = dt.Columns.Count;

for (int i = 0; i <dt.Rows.Count; i++)

{

    excelSheet.get_Range(excelSheet.Cells[i+1,1], excelSheet.Cells[i+1, colCount]).Value2 = dt.Rows[i].ItemArray;

      }
}

这就有了很大进步,效率与数据列的多少已经无关了,对于这个改进我在网上还没有看到,为此我还曾沾沾自喜,但是这个方法的效率依然不高,尤其是灵活性不够。

以上效率的损失主要是每导出一条记录都要与Excel交互一次,如果我们把数据准备好一次性写入Excel是否效率更快?看如下程序:

public void DataTableToExcel(DataTable dt)

{      

    int rowCount = dt.Rows.Count;

int colCount = dt.Columns.Count;

object[,] dataArray = new object[rowCount,colCount];

for (int i = 0; i <rowCount; i++)

{

for (int j=0;j<colCount;j++)

{

            dataArray[i, j] = dt.Rows[i][j];

         }

}

excelSheet.get_Range("A1", excelSheet.Cells[rowCount, colCount]).Value2 = dataArray;

}

原创粉丝点击