2015-12-02 110 views
-1

我想用某個標題將DataTable導出爲ex​​cel。我正在使用XLWorkbook導出爲Excel。我的代碼導出DataTable excel完美,但我不知道如何添加一些標題。使用XL工作簿在c#中使用標題導出Excel

我根據數據表中的列大小,然後後添加的數據錶行希望Excel像下面

I want Excel Like that

,這裏是我的C#代碼

public void ExportDataToExcel(DataTable dt, string fileName) 
    {           
      using (XLWorkbook wb = new XLWorkbook()) 
      { 
       wb.Worksheets.Add(dt);      
       wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; 
       wb.Style.Font.Bold = true; 

       Response.Clear(); 
       Response.Buffer = true; 
       Response.Charset = ""; 
       Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
       Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx"); 

       using (MemoryStream MyMemoryStream = new MemoryStream()) 
       { 
        wb.SaveAs(MyMemoryStream); 
        MyMemoryStream.WriteTo(Response.OutputStream); 
        Response.Flush(); 
        Response.End(); 
       } 
      }      
    } 

回答

0

添加行,合併單元格。

+0

我不知道合併行和cells.could你幫我... – satyender

1

這是如何合併的Excel的工作表的第一行的單元格:

//select first row 
    Microsoft.Office.Interop.Excel.Range firstRow = Worksheet.UsedRange.Rows[1]; 
    //merge the cells of the first row 
    firstRow.Merge(); 
    //set the first rows backcolor to gray 
    firstRow.Interior.Color = System.Drawing.Color.Gray;enter code here 
    //set the textcolor of the first row to white 
    firstRow.Font.Color = System.Drawing.Color.White; 
    //set the text to the center of the merged cells 
    firstRow.HorizontalAlignment = XlHAlign.xlHAlignCenter; 
    firstRow.VerticalAlignment = XlVAlign.xlVAlignCenter; 

我希望這有助於!

相關問題