简体   繁体   English

C#OpenXml Excel创建-我可以将其设置为“格式化为表格”吗?

[英]C# OpenXml Excel Creation - can I set it to “Format as table”?

When I am creating an Excel sheet using DocumentFormat.OpenXml is there any way to specify that I want a range of cells (really the whole sheet) to be in the "Format as Table" (CTRL+T) representation? 当我使用DocumentFormat.OpenXml创建Excel工作表时,是否有任何方法可以指定我希望某个单元格区域(实际上是整个工作表)采用“表格格式”(CTRL + T)表示形式? Or is this not available in the OpenXML library? 还是在OpenXML库中不可用? I can't seem to find anything that says either way. 我似乎找不到任何能说明任何问题的信息。 Thank you. 谢谢。

While I'm pretty sure you can do what you want purely with the OpenXML library, you also have the option of including the ClosedXML library which makes working with Excel a whole lot easier. 虽然我很确定您可以完全使用OpenXML库完成您想做的事情,但您也可以选择包含ClosedXML库,这使使用Excel变得更加容易。

If I understand your question correctly, you are just looking for taking a data set of some kind and dump it as a table in a Excel-file, in which case, if you can boil your data down to a DataTable in C# the following should help you 如果我对问题的理解正确,那么您只是在寻找某种数据集并将其作为表转储到Excel文件中,在这种情况下,如果您可以将数据分解为C#中的DataTable,则应该帮你

//create some dummy table for this test
DataTable table = new DataTable();
//make a few columns
table.Columns.AddRange(
    new DataColumn[] { new DataColumn("Column 1",typeof(int)),
    new DataColumn("Column 2", typeof(int)),
    new DataColumn("Column 3", typeof(int)) }
);
//populate with some randomness
Random r = new Random();
for (int i = 0; i < 100; i++)
{
    var newRow = table.NewRow();
    newRow[0] = r.Next(0, 10);
    newRow[1] = r.Next(0, 10);
    newRow[2] = r.Next(0, 10);
    table.Rows.Add(newRow);
}
//create workbook
XLWorkbook wb = new XLWorkbook();
var sheet = wb.AddWorksheet("My datatable");
//just showing how to add a bit of extra data to the sheet, not required
sheet.Cell(1, 1).SetValue<string>("Title: this is just a test");
sheet.Cell(1, 3).SetValue<string>("Date: " + DateTime.Now);
//dump table in sheet
sheet.Cell(2, 1).InsertTable(table);
sheet.Columns().AdjustToContents();
wb.SaveAs(@"c:\test\dtable.xlsx",false);

This will result in the following Excel-document 这将导致以下Excel文档 测试程序输出的示例

I hope this helps! 我希望这有帮助!

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

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