简体   繁体   English

使用 OpenXml 填充表格

[英]Populate table with OpenXml

I want to create an Excel template file, and then open it and populate it with data from code using OpenXml.我想创建一个 Excel 模板文件,然后打开它并使用 OpenXml 用代码中的数据填充它。

Is it possible to create the table in Excel, and then populate that table by name from code?是否可以在 Excel 中创建表格,然后从代码中按名称填充该表格?

I want to be able to refer to the table by name.我希望能够按名称引用该表。 Ideally, this will allow me to insert rows and the table would get taller to accommodate those rows.理想情况下,这将允许我插入行,并且表格会变高以容纳这些行。 And any table header or footer would remain intact.任何表格页眉或页脚都将保持不变。

I'm new to working with OpenXML.我是 OpenXML 的新手。 If this is possible, can someone point me to some documentation on how to do it?如果这是可能的,有人可以指点我一些有关如何操作的文档吗?

Yes, this is possible with OpenXml.是的,这可以通过 OpenXml 实现。 Basically, if the table already exists you just need to write the required data, find the table and then update the Reference property of the table to reflect the cells the table now covers.基本上,如果表格已经存在,您只需要写入所需的数据,找到表格,然后更新表格的Reference属性以反映表格现在涵盖的单元格。

A Table exists inside a TableDefinitionPart which can be found from the Worksheetpart .一个Table存在于TableDefinitionPart ,可以从Worksheetpart找到它。 That sounds complicated but finding the correct table isn't too bad.这听起来很复杂,但找到正确的表格还不错。

Assuming you have a table in column A with no data other than the header and named MyTable in an existing Excel file like this假设您在 A 列中有一个表格,除了标题之外没有其他数据,并且在这样的现有 Excel 文件中命名为MyTable

前

The following will add some data to the table:以下将向表中添加一些数据:

using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, true))
{
    WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
    Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == "Sheet1").First();
    WorksheetPart worksheetPart = workbookPart.GetPartById(sheet.Id) as WorksheetPart;
    SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();

    //write some new data
    for (int i = 1; i < 11; i++)
    {
        //rowIndex takes into account the header (i.e. we're filling A2-A11)
        uint rowIndex = (uint)i + 1;
        Row row = new Row() { RowIndex = rowIndex };
        Cell cell = new Cell() { CellReference = $"A{rowIndex}", CellValue = new CellValue(i), DataType = CellValues.Number };
        row.Append(cell);

        sheetData.Append(row);
    }
    //find the table
    Table table = worksheetPart.TableDefinitionParts.FirstOrDefault(t => t.Table.Name == "MyTable")?.Table;
    //update the reference of the table (11 is 10 data rows and 1 header)
    table.Reference = "A1:A11";
}

Giving a result like this:给出这样的结果:

后

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

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