2012-02-02 78 views
2

我对此很陌生,当我尝试向一行添加多个单元格时,它说有不可读的内容。这是我的。将多个单元格添加到单个行中

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(); 

如果我删除第二个单元格,它按预期方式工作。

回答

4

而不是 “A2” 的单元格引用应该是 “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") 
     }; 
0

我有一个类似的问题。如果有人想要将单元格插入同一列,则需要将行索引加1并单元格引用,以便将单元格插入到同一列中。花了我整个周末弄清楚: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); 

最好是使用循环。