C# 导出excel
public bool ExportExcel(DataSet ds, string filePath)
{
bool result = true;
try
{
Application xlApp = new Application();
object missing = System.Reflection.Missing.Value;
Workbooks workbooks = xlApp.Workbooks;
Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
worksheet.Name = "发现者报告";
worksheet.Columns[4].ColumnWidth = 40;
int t = 2;
int c = 2;
for (int i = 0; i < ds.Tables.Count; i++)
{
worksheet.Cells[t - 1, c] = ds.Tables[i].TableName;
Range range;
range = (Range)worksheet.Cells[t,c];
range.Interior.Color = System.Drawing.Color.DarkSeaGreen;
range.Font.Bold = true;
range.Borders.Weight = 2;
range.Columns.ColumnWidth = 40;
for (int j = 0; j < ds.Tables[i].Columns.Count; j++)
{
worksheet.Cells[t, j + c] = ds.Tables[i].Columns[j].Caption;
// Range range;
range = (Range)worksheet.Cells[t, j + c];
range.Interior.Color = System.Drawing.Color.DarkSeaGreen;
range.Font.Bold = true;
range.Borders.Weight = 2;
range.Columns.ColumnWidth = 40;
}
t++;
for (int j = 0; j < ds.Tables[i].Rows.Count; j++, t++)
{
for (int k = 0; k < ds.Tables[i].Columns.Count; k++)
{
worksheet.Cells[t, k + c] = ds.Tables[i].Rows[j][k];
// Range range;
range = (Range)worksheet.Cells[t, k + c];
range.Interior.Color = System.Drawing.Color.Khaki;
range.Borders.Weight = 2;
range.Columns.ColumnWidth = 40;
}
}
t++;
}
worksheet.SaveAs(filePath, missing, missing, missing, missing, missing, missing, missing, missing);
workbook.Close(missing, missing, missing);
xlApp.Quit();
}
catch (Exception e) {
}
return result;
}
}