DataTable导出Excel
程序员的工资少,所以代码也不想写多,搞了几行就把导出Excel功能实现了!-_-#
这个也可以重写一下,换成控件导出Excel,只要取出DataSource就行了,原理一样!
public static void ExportExcel(DataTable eDataTable)
{
try
{
Excel.ApplicationClass ExcelApp;
ExcelApp = new Excel.ApplicationClass();
Excel.Workbook ExcelBook = ExcelApp.Workbooks.Add(1);
Excel.Worksheet ExcelSheet = (Excel.Worksheet)ExcelBook.Worksheets[1];
ExcelApp.Visible = true;
//写列标题
for (int i = 0; i < eDataTable.Columns.Count; i++)
{
ExcelSheet.Cells[1, i + 1] = eDataTable.Columns[i].ColumnName;
}
//写值
for (int r = 0; r < eDataTable.Rows.Count; r++)
{
for (int i = 0; i < eDataTable.Columns.Count; i++)
{
ExcelSheet.Cells[r + 2, i + 1] = eDataTable.Rows[r][i];
}
}
}
catch (Exception ex)
{
ErrLog.ExcelErr(ex.ToString());
}
finally
{
GC.Collect();
}
}
{
try
{
Excel.ApplicationClass ExcelApp;
ExcelApp = new Excel.ApplicationClass();
Excel.Workbook ExcelBook = ExcelApp.Workbooks.Add(1);
Excel.Worksheet ExcelSheet = (Excel.Worksheet)ExcelBook.Worksheets[1];
ExcelApp.Visible = true;
//写列标题
for (int i = 0; i < eDataTable.Columns.Count; i++)
{
ExcelSheet.Cells[1, i + 1] = eDataTable.Columns[i].ColumnName;
}
//写值
for (int r = 0; r < eDataTable.Rows.Count; r++)
{
for (int i = 0; i < eDataTable.Columns.Count; i++)
{
ExcelSheet.Cells[r + 2, i + 1] = eDataTable.Rows[r][i];
}
}
}
catch (Exception ex)
{
ErrLog.ExcelErr(ex.ToString());
}
finally
{
GC.Collect();
}
}