2017-08-04 46 views
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); 
     } 
     } 
     } 

回答

0
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"; 
0

示例應用程序增加了一個頭或者在您提供的文檔中添加頁腳,請在示例中調用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);