ClosedXML Insert data from List into existing proper Excel Table (named range) c#

时间:2018-06-04 16:59:12

标签: c# excel closedxml

There was a similar question, it didn't seem answered (maybe there's not an answer). How do you "update" an existing Excel Table (named range) from Closed XML. I know how to get the table info, and delete the existing data (see below)

    var ws = wb.Worksheet(sheetName);
    var table = ws.Table("data");
    table.Clear();

then ?? I have a list called "listdata" per say, which matches the table headers exactly...

Do I need to loop through the table one at a time like this (which seems like a waste):

foreach (var item in listdata){table.InsertRowsBelow(1); ws.Cells(2,1).InsertData(item)}

I guess maybe it would be kinda simpler if you did something like this:

table.InsertRowsBelow(listdata.Count()); ws.Cells(2,1).InsertData(listdata);

Or is there a way to bulk load into "table" (similar to .AddRange(listdata) or .Union(listdata)). Currently, I just delete the entire sheet then recreate the sheet and paste the new table:

      wb.Worksheets.Delete(sheetName);
      var ws = wb.Worksheets.Add(sheetName);
      ws.Cell(1, 1).InsertTable(listdata, "data", true);

2 个答案:

答案 0 :(得分:0)

据我所知,您在答案中讨论的方法是最简单的方法,即

  • 获取对该表的引用
  • 删除其数据
  • 插入您的列表。

InsertData用作批量插入,它将获取任何IEnumerable集合并将整个集合从所选单元格开始输出到Excel电子表格中。

因此,例如,您可以执行以下操作从列表(其中工作表的第一行是表的标题行)中填充表:

private void PopulateTable(XLWorkbook wb, string workSheetName, string tableName, IEnumerable list)
{
    var ws = wb.Worksheet(workSheetName);
    var table = ws.Table(tableName);

    ws.Cell(2, 1).InsertData(list);
}

Cell还具有InsertTable函数,该函数将插入DataTable而不是IEnumerable

答案 1 :(得分:0)

https://github.com/ClosedXML/ClosedXML/pull/932中,对IXLTable进行了一些补充。您可能对IXLTable.ReplaceData(data)IXLTable.AppendData(data)感兴趣。