如何使用closedxml在一个工作表中添加多个数据表?

5

我有多个包含数据的数据表,我想将它们添加到单个带有空格的工作表中。我正在使用ClosedXML来开发导出Excel工具。

2个回答

5
我已经完成了下面的代码。
 wb.Worksheets.Add(dt);
 wb.Worksheet(1).Cell(5, 1).InsertTable(dt1);

1

如果您有一个List<DataTable>,以下是如何动态添加的方法:

int currentRow = 1;//counter to keep track of what row we're on
IXLWorksheet worksheet = wb.AddWorksheet(sheetName: settings.sheetName);
foreach (DataTable table in tables)
{
    //Use the table name, and add it to the first cell above the table before insert
    worksheet.Cell(currentRow, 1).Value = table.TableName;
    worksheet.Cell(currentRow, 1).Style.Font.FontSize = 20;
    worksheet.Cell(currentRow, 1).Style.Font.SetBold();
    currentRow++;
    //now that the title is inserted and formatted, insert table
    worksheet.Cell(currentRow, 1).InsertTable(table);
    currentRow += table.Rows.Count + 3;
}
//optional for adjusting columns to their contents and setting wrap text
var cols = worksheet.Columns();
cols.AdjustToContents();
foreach(var a in cols)
{//set mas width to 50
    a.Width = a.Width > 50 ? 50 : a.Width;
}
cols.Style.Alignment.WrapText = true;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接