简体   繁体   English

使用C#将数据表导出到Excel时格式化表

[英]Format Table while Export the datatable To Excel using c#

I am confusing to format the datatable while exporting it to excel 在将数据表导出到excel时,我难以格式化数据表

My Code 我的密码

var workBook = new ExpertXls.ExcelLib.ExcelWorkbook(ExpertXls.ExcelLib.ExcelWorkbookFormat.Xlsx_2007);
workBook.Worksheets.AddWorksheet();
var workSheet = workBook.Worksheets[0];
workSheet.LoadDataTable(ds.Tables[0], 1, 1, true);
workSheet.AutofitColumns();
context.Response.Clear();
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.ContentType = 
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
using (var MyMemoryStream = new MemoryStream())
{
    workBook.Save(MyMemoryStream);
    MyMemoryStream.WriteTo(context.Response.OutputStream);
    context.Response.Flush();
    context.Response.End();
}

The Above code works fine to export the datatable to excel without formating. 上面的代码可以很好地将数据表导出为ex​​cel,而无需格式化。

And i can able to set the Cell Font Color as, 我可以将“单元字体颜色”设置为

workSheet["A1:N1"].Style.Font.Color = System.Drawing.Color.Green;

Then, how to get the worksheet cells and set its back color? 然后,如何获取工作表单元格并设置其底色?

i tried but not able to get the cells 我试过但没办法弄牢房

workSheet.

here can get the cells not style 这可以使单元格不样式

worksheet["A1:N1"].Cells.

I downloaded the Nuget Package of the library you're using, since their documentation is non-existent online. 我下载了您正在使用的库的Nuget软件包,因为在线上不存在它们的文档。

Could you try the following to achieve what you want: 您可以尝试以下方法实现所需的功能:

workSheet["A1:N1"].Style.Fill.FillType = ExpertXls.ExcelLib.ExcelCellFillType.SolidFill;
workSheet["A1:N1"].Style.Fill.SolidFillOptions.BackColor = System.Drawing.Color.Green;

Change Green to the color of your choice, and let me know if it works. Green更改为您选择的颜色,然后让我知道它是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM