Excel add data to WorksheetPart in code behind

狂风中的少年 提交于 2019-12-04 03:34:10
private static void InsertValuesInWorksheet(WorksheetPart worksheetPart, IEnumerable<string> values)
{
    var worksheet = worksheetPart.Worksheet;
    var sheetData = worksheet.GetFirstChild<SheetData>();
    var row = new Row { RowIndex = 1 };  // add a row at the top of spreadsheet
    sheetData.Append(row);

    int i = 0;
    foreach (var value in values)
    {
        var cell = new Cell
                            {
                                CellValue = new CellValue(value),
                                DataType = new EnumValue<CellValues>(CellValues.String)
                            };

        row.InsertAt(cell, i);
        i++;
    }
}

This method will add a new row to a specified worksheet and fill the row's cells with the values from an array. In your code sample, it could be called like this:

var values = new[] {"foo", "bar", "baz"};

InsertValuesInWorksheet(newWorksheetPart1, values);
InsertValuesInWorksheet(newWorksheetPart2, values);
InsertValuesInWorksheet(newWorksheetPart3, values);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!