我想用一些标题将DataTable导出为excel。我正在使用XLWorkbook导出到excel。我的代码导出DataTable完美excel但我不知道如何添加一些标题。
我想像下面这样的Excel
这是我的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 :(得分:1)
这是如何合并excel-worksheet的第一行的单元格:
//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;
我希望这有帮助!
答案 1 :(得分:0)
根据数据表列大小添加行和合并单元格,然后在此之后添加数据表行。
答案 2 :(得分:0)
if(callrec !=null)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[7] {
new DataColumn("RECORDING FILE NAME",typeof(string)),
new DataColumn("ACCOUNT NUMBER",typeof(string)),
new DataColumn("CALL START TIME",typeof(string)),
new DataColumn("AGENT NAME",typeof(string)),
new DataColumn("AGENT RESULT",typeof(string)),
new DataColumn("DURATION SECONDS",typeof(string)),
new DataColumn("PHONE DIALED",typeof(string))
});
foreach (var item in callrec)
{
dt.Rows.Add(item.RecFileName,
item.AccountNo == "NULL" ? "":item.AccountNo,
item.CallStartTime == null ? null : item.CallStartTime,
item.agentName=="NULL"? "":item.agentName,
item.agentResults=="NULL"?"":item.agentResults,
item.DurationSecs,
item.phoneDialed=="NULL"?"":item.phoneDialed
);
};
//Code For Closed XML
using ( XLWorkbook wb= new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt, "CallRecordingData");
ws.Tables.FirstOrDefault().ShowAutoFilter = false;
MemoryStream stream = GetStream(wb);
// Response.Clear();
// Response.Buffer = true;
// Response.Charset = "";
// Response.ContentType = "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet";
// Response.AddHeader("content-disposition",
"attachment;filename=" + fileName + ".xlsx");
}
}