2015-12-02 71 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; 

我希望这有助于!

相关问题