.NET中导出Excel的方法大致有三类,一是导出文本文件(csv),或者导出符合某种格式的xml文件,例如此文介绍的Export a DataSet to Microsoft Excel without the use of COM objects;二是利用Ado.NET,没用过,据说效率不高。三是利用COM。这三类方法第三种是最自由的,可以设置Excel单元格的格式等等,几乎可以完全控制整个Excel。前两种方法适合于导出的数据对格式没有任何要求的情况。
下面主要介绍第三种方法。首先需要加入一个引用:
Code Snippet
- using Microsoft.Office.Interop.Excel;
将Datatable导出到Excel的代码是很直观的:
Code Snippet
- public static bool Export(System.Data.DataTable data, string file)
- {
- Application app = new Microsoft.Office.Interop.Excel.Application();
- try
- {
- if (app == null)
- {
- throw new Exception("new Microsoft.Office.Interop.Excel.Application() returns null");
- }
- else
- {
- Workbooks xlBooks = app.Workbooks;
- Workbook xlBook = xlBooks.Add(XlWBATemplate.xlWBATWorksheet);
- Worksheet xlSheet = xlBook.Worksheets[1] as Worksheet;
- int n=1;
- foreach (System.Data.DataColumn col in data.Columns)
- {
- xlSheet.Cells[1, n++] = col.ColumnName;
- }
- int row = 2;
- foreach (System.Data.DataRow r in data.Rows)
- {
- int column = 1;
- foreach (System.Data.DataColumn col in data.Columns)
- {
- xlSheet.Cells[row, column] = data.Rows[row-2].ItemArray[column - 1];
- column++;
- }
- row++;
- }
- object missing = System.Reflection.Missing.Value;
- xlSheet.SaveAs(file, missing, missing, missing,
- missing, missing, missing, missing, missing, missing);
- }
- return true;
- }
- catch (Exception e)
- {
- Logger.Log(e);
- return false;
- }
- finally
- {
- app.Quit();
- GC.Collect();
- }
- }
但是这样操作非常非常慢。在存入数据的时候不能一个一个单元格设置,可以用一个二维数组对一个Range设置,具体方法如下:
Code Snippet
- Workbooks xlBooks = app.Workbooks;
- Workbook xlBook = xlBooks.Add(XlWBATemplate.xlWBATWorksheet);
- Worksheet xlSheet = xlBook.Worksheets[1] as Worksheet;
- int n=1;
- foreach (System.Data.DataColumn col in data.Columns)
- {
- xlSheet.Cells[1, n++] = col.ColumnName;
- }
- // int row = 2;
- int row = 0;
- object[,] arr = new object[data.Rows.Count, data.Columns.Count];
- foreach (System.Data.DataRow r in data.Rows)
- {
- //int column = 1;
- int column = 0;
- foreach (System.Data.DataColumn col in data.Columns)
- {
- //xlSheet.Cells[row, column] = data.Rows[row-2].ItemArray[column - 1];
- arr[row, column] = data.Rows[row][column];
- column++;
- }
- row++;
- }
- Range range=(Range)xlSheet.Cells[2, 1];
- range=range.get_Resize(data.Rows.Count,data.Columns.Count);
- range.Value2= arr;
- object missing = System.Reflection.Missing.Value;
- xlSheet.SaveAs(file, missing, missing, missing,
- missing, missing, missing, missing, missing, missing);
上面仅贴出了关键部分。