![](/img/trans.png)
[英]issues while exporting data from excel by using linqtoexcel in c#
[英]how to add header while exporting data table to excel C#
這是我的代碼,效果很好,但是如何在這種方法中為Excel文件添加標題
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);
}
}
}
Excel.Range headerRange = xlWorkSheet1.get_Range("A1", "V1");
headerRange.HorizontalAlignment =
Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange.Value = "Header text 1";
headerRange = xlWorkSheet2.get_Range("A1", "V1");
headerRange.HorizontalAlignment =
Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange.Value = "Header text 2";
該示例應用程序在您提供的文檔中添加頁眉或頁腳,並調用示例中的XLInsertHeaderFooter方法來完成工作。 該方法使您可以添加頁眉或頁腳,以指示該頁眉應出現在哪一組頁面上。
const string fileName = @"C:\temp\test.xlsx"
XLInsertHeaderFooter(fileName, "Sheet1",
"This is my header", HeaderType.EvenHeader);
XLInsertHeaderFooter(fileName, "Sheet1",
"This is my footer", HeaderType.AllFooter);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.