Excel add data to WorksheetPart in code behind

后端 未结 1 687
旧时难觅i
旧时难觅i 2021-02-15 18:09

Hello guys I am creating an Excel file with 3 worksheets in the following code.

using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Create(path + @\"\\U         


        
1条回答
  •  后悔当初
    2021-02-15 18:39

    private static void InsertValuesInWorksheet(WorksheetPart worksheetPart, IEnumerable values)
    {
        var worksheet = worksheetPart.Worksheet;
        var sheetData = worksheet.GetFirstChild();
        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.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);
    

    0 讨论(0)
提交回复
热议问题