DataTable匯出成Excel
網上能搜到許多DataTable匯出EXCEL的文章,但實施起來,可行者不多也!我調試了一番,問題得以解決,現在此整理與大家分享:
一、實現目標:
由一個記憶體表DataTable,匯出欄位名及其內容的完整EXCEL表格
二、實施步驟:
1、添加引用:
這是非常生要的一步,很多人調試不成都是因為這步沒做好:
需要在你的解決方案中添加COM引用,選擇 "Microsoft EXCEL ...."(根據版本有所不同),這是為下面的 EXCEL相關命名空間的引用做鋪墊的;
我用的EXCEL 2007,添加COM引用後如:
增加了兩個引用檔案!
2、命名空間引用部分:
增加下面的引用內容:
using Microsoft.Office.Interop.Excel;
3、定義函數:
public static void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
{
if (tmpDataTable == null)
return;
int rowNum = tmpDataTable.Rows.Count;
int columnNum = tmpDataTable.Columns.Count;
int rowIndex = 1;
int columnIndex = 0;
Application xlApp = new ApplicationClass();
xlApp.DefaultFilePath = "";
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 1;
Workbook xlBook = xlApp.Workbooks.Add(true);
//將DataTable的列名匯入Excel表第一行
foreach (DataColumn dc in tmpDataTable.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
}
//將DataTable中的資料匯入Excel中
for (int i = 0; i < rowNum; i++)
{
rowIndex++;
columnIndex = 0;
for (int j = 0; j < columnNum; j++)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();
}
}
//xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));
xlBook.SaveCopyAs(strFileName);
}
4、 使用執行個體:
System.Data.DataTable dt = ……; //準備好你的DataTable
DataTabletoExcel(dt, "C:\\\\中國.XLS"); //調用自訂的函數,當然輸出檔案你可以隨便寫
三、測試環境:
VS2008,EXCEL 2007
其實Excel的版本是2003與2007都無所謂,主要是看你添加進來的庫檔案版本適合不適合