您的位置:首页 > 其它

Datatable 直接生成 Excel 文件到本地磁盘中

2012-09-15 11:11 363 查看
protected void DatatableExcelC(System.Data.DataTable dt)
{
Microsoft.Office.Interop.Excel.Application excelkccx = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel._Workbook wb;
Microsoft.Office.Interop.Excel._Worksheet ws = null;
wb = excelkccx.Workbooks.Add(true);
string tbname = "FileName";

if (ws == null)
{
ws = (_Worksheet)wb.Worksheets.Add(Type.Missing, Type.Missing, 1, Type.Missing);
}
else
{
ws = (_Worksheet)wb.Worksheets.Add(Type.Missing, ws, 1, Type.Missing);
}
int row = 2;
for (int i = 0; i < dt.Columns.Count; i++)
{
excelkccx.Cells[1, i + 1] = dt.Columns[i].ColumnName.ToString();
}
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
excelkccx.Cells[row, j + 1] = dt.Rows[i][j].ToString();
}
row++;
}
wb.SaveCopyAs("C:\\" + tbname + ".xls");
wb.Close(false, null, null);
excelkccx.Quit();
wb = null;
ws = null;
excelkccx = null;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: