protected void ExportExcel(DataTable dt)
{
string fileName = “FileName”;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
int rowIndex = ;//列
int colIndex = ;//行
excel.Application.Workbooks.Add(true);
foreach (DataColumn col in dt.Columns)
{
colIndex++;
excel.Cells[, colIndex] = col.ColumnName;
excel.get_Range(excel.Cells[, colIndex], excel.Cells[, colIndex]).HorizontalAlignment = ;//设置第一行每一列内容居中显示
}
foreach (DataRow row in dt.Rows)
{
rowIndex++;
colIndex = ;
for (colIndex = ; colIndex < dt.Columns.Count; colIndex++)
{
excel.Cells[rowIndex, colIndex + ] = row[colIndex].ToString();
excel.get_Range(excel.Cells[rowIndex, colIndex + ], excel.Cells[rowIndex, colIndex + ]).HorizontalAlignment = ;//设置从第二行开始每一列内容右对齐显示
}
}
excel.Columns.EntireColumn.AutoFit();
excel.Visible = false;
excel.ActiveWorkbook.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
excel.Quit();
excel = null;
GC.Collect();//垃圾回收
}
}