1
這是我的代碼工作正常,但如何在這個方法中添加標題爲Excel文件如何添加標題,同時將數據導出表到Excel C#
public void ExportToExcel()
{
DataTable Tbl = new DataTable();
Tbl = dt;
OpenFileDialog openDlg = new OpenFileDialog();
System.Windows.Forms.SaveFileDialog saveDlg = new
System.Windows.Forms.SaveFileDialog();
if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = saveDlg.FileName;
try
{
if (Tbl == null || Tbl.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
Microsoft.Office.Interop.Excel.Application excelApp = new
Microsoft.Office.Interop.Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Microsoft.Office.Interop.Excel._Worksheet workSheet =
excelApp.ActiveSheet;
// column headings
for (int i = 0; i < Tbl.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName;
}
// rows
for (int i = 0; i < Tbl.Rows.Count; i++)
{
// to do: format datetime values before printing
for (int j = 0; j < Tbl.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
}
}
// check fielpath
if (path != null && path != "")
{
try
{
workSheet.SaveAs(path);
excelApp.Quit();
MessageBox.Show("Excel file saved!");
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: Excel file could not be saved! Check
filepath.\n"+ ex.Message);
}
}
else // no filepath is given
{
excelApp.Visible = true;
}
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: \n" + ex.Message);
}
}
}