Adding multiple Cells to a single Row

瘦欲@ 提交于 2019-12-07 11:54:46

问题


I am new to this and when I try to add more than one cell to a row it says there is unreadable content. Here is what I have.

SpreadsheetDocument ssDoc = SpreadsheetDocument.Create(saveFile, SpreadsheetDocumentType.Workbook);

// Add a WorkbookPart to the document
WorkbookPart workbookPart = ssDoc.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
// Add a WorksheetPart to theWorkbookPart
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());

Sheets sheets = ssDoc.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

Sheet sheet = new Sheet()
{   Id = ssDoc.WorkbookPart.GetIdOfPart(worksheetPart),
    SheetId = 1, Name = "Sheet1"
};

sheets.Append(sheet);
Worksheet worksheet = new Worksheet();
SheetData sheetData = new SheetData();
Row row = new Row();

Cell cell = new Cell()
{
    CellReference = "A1",
    DataType = CellValues.String,
    CellValue = new CellValue("Cell1")
};

Cell cell2 = new Cell()
{
    CellReference = "A2",
    DataType = CellValues.String,
    CellValue = new CellValue("Cell2")
};
row.Append(cell);
row.Append(cell2);

sheetData.Append(row);
worksheet.Append(sheetData);
worksheetPart.Worksheet = worksheet;
// Close the document.
ssDoc.Close();

If I remove the second cell, it works as expected.


回答1:


Instead of "A2" the cell reference should be "B1"

        SpreadSheet.Cell cell = new SpreadSheet.Cell()
        {
            CellReference = "A1",
            DataType = SpreadSheet.CellValues.String,
            CellValue = new SpreadSheet.CellValue("Cell1")                 
        };

        SpreadSheet.Cell cell2 = new SpreadSheet.Cell()
        {
            CellReference = "B1",
            DataType = SpreadSheet.CellValues.String,
            CellValue = new SpreadSheet.CellValue("Cell2")
        };



回答2:


I had a similar issue. If anyone wants to insert cells in the same column, Row Index needs to be incremented and cell reference in order to insert cell in the same column. Took me entire weekend to figure out :D

 Row row2 = new Row { RowIndex = 2};
 SpreadSheet.Cell cell2 = new SpreadSheet.Cell()
    {
        CellReference = "B1",
        DataType = SpreadSheet.CellValues.String,
        CellValue = new SpreadSheet.CellValue("Cell2")
    };

row2.Append(cell2);
sheetData.Append(row);

It's better to use loop.



来源:https://stackoverflow.com/questions/9117013/adding-multiple-cells-to-a-single-row

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