using Microsoft.Office.Interop.Excel; 引用命名空间
public bool DataToExcel(System.Data.DataTable dataTable)
{
Application excel = new Application();
try
{
object missingValue = Missing.Value;
excel.Visible = false;
_Workbook workBook = excel.Workbooks.Add(missingValue);
//加入模板可这样写
//string path = AppDomain.CurrentDomain.BaseDirectory;
// _Workbook workBook = excel.Workbooks.Add(path+"\\App_Data\\MJ_Template.xlsx");
// _Worksheet sheet = workBook.Worksheets[1];//下面excel对象改成sheet就行
int excelRow =0;
int excelColumn = 0;
for (int rowIndex = 0; rowIndex <dataTable.Rows.Count; rowIndex++)
{
for (int columnIndex = 0; columnIndex<dataTable.Columns.Count; columnIndex++)
{
excelRow = rowIndex + 1;
excelColumn = columnIndex + 1;
if (excelRow == 1)
{
excel.Cells[excelRow, excelColumn] = dataTable.Columns[columnIndex].ColumnName;//load 表头
}
else
{
excel.Cells[excelRow, excelColumn] = dataTable.Rows[rowIndex][columnIndex];
}
}
}
workBook.SaveAs(@"D:\ExcelTable.xls", missingValue, null, null,false, false, XlSaveAsAccessMode.xlNoChange, null, null, null,null);
workBook.Close(false, missingValue, missingValue);
excel.Quit();
return true;
}
catch(Exception exception)
{
return false;
}
finally
{
excel.Quit();
}
}