// 创建 Excel
Excel.Application _excelApp = new Excel.Application();
// Missing.Value 在System.Reflection 命名空间中
// Missing.Value 还可以改成Excel模版
Excel.Workbook _excelWorkbook = _excelApp.Workbooks.Add(Missing.Value);
// 获取sheet
Excel.Worksheet _excelSheet = (Excel.Worksheet)(_excelWorkbook.ActiveSheet);
// 要填充的内容
string[,] sTbArray = new string[100, 5];
// 对内容sTbArray进行赋值
// 获取范围并且赋值
_excelSheet.get_Range(_excelSheet.Cells[1, 1],
_excelSheet.Cells[100, 5]).Value = ((object)(sTbArray));
// 不显示询问对话框
_excelApp.DisplayAlerts = false;
// 保存
_excelWorkbook.SaveAs(sServePath,
Missing.Value,
Missing.Value,
Missing.Value,
Missing.Value,
Missing.Value,
Excel.XlSaveAsAccessMode.xlNoChange,
Missing.Value,
Missing.Value,
Missing.Value,
Missing.Value);
// quit
_excelApp.Quit();
--------------------------------------------------------------------
或:
foreach(DataTable dt in ds.Tables)
{
ExportDataTable(dt);
}
public void ExportDataTable(DataTable table)
{
// Starts excel and gets an excel application object.
Excel.Application excel = new Excel.Application();
// Adds a new workbook to the excel application.
Excel.Workbook book = excel.Workbooks.Add(Missing.Value);
Excel.Worksheet sheet = (Excel.Worksheet)book.ActiveSheet;
// Adds table headers
for(int col = 0; col < table.Columns.Count; col++)
{
sheet.Cells[1, col + 1] = table.Columns[col].ColumnName;
}
for(int row = 0; row < table.Rows.Count; row++)
{
for(int col = 0; col < table.Columns.Count; col++)
{
sheet.Cells[row + 2, col + 1] = table.Rows[row][col].ToString();
}
}
// Saves and cloeses the workbook;
book.Close(true, "C://fx.xls", Missing.Value);
// Exit excel application.
excel.Quit();
}