写入 Excel 内容,参数:excelTable 是要导入 excel 的一个 table
表
1. public static bool SaveDataTableToExcel(System.Data.DataTable excelTable, strin
g filePath)
2.
{
3.
Microsoft.Office.Interop.Excel.Application app =
4.
new Microsoft.Office.Interop.Excel.ApplicationClass();
5.
try
6.
{
7.
app.Visible = false;
8.
Workbook wBook = app.Workbooks.Add(true);
9.
Worksheet wSheet = wBook.Worksheets[1] as Worksheet;
10.
if (excelTable.Rows.Count > 0)
11.
{
12.
int row = 0;
13.
row = excelTable.Rows.Count;
14.
int col = excelTable.Columns.Count;
15.
for (int i = 0; i < row; i++)
16.
{
17.
for (int j = 0; j < col; j++)
18.
{
19.
string str = excelTable.Rows[i][j].ToString();
20.
wSheet.Cells[i + 2, j + 1] = str;
21.
}
22.
}
23.
}
24.
25.
int size = excelTable.Columns.Count;
26.
for (int i = 0; i < size; i++)
27.
{
28.
wSheet.Cells[1, 1 + i] = excelTable.Columns[i].ColumnName;
29.
}
30.
//设置禁止弹出保存和覆盖的询问提示框
31.
app.DisplayAlerts = false;
32.
app.AlertBeforeOverwriting = false;
33.
//保存工作簿
34.
wBook.Save();
35.
//保存 excel 文件
36.
app.Save(filePath);
37.
app.SaveWorkspace(filePath);
38.
app.Quit();
39.
app = null;