我是新来的OpenXML,并已与行后添加一个新行,在A1单元格数据(与细胞数据)的已添加挣扎。
所以基本上我想在“第2行”列“A1”插入“测试”,在“第1行”列“A1”和“测试”。
这里是我的代码,它看起来声音,并创建文件却Excel不会打开它。 我的OpenOffice打开它,它只能显示一行,而不是两个。 当我注释掉追加2行至sheetdata,它工作正常。 所以我想我错误地创建了第二排。 任何帮助表示赞赏。 先感谢您。 下面是代码:
using (SpreadsheetDocument spreadSheetDocument =
SpreadsheetDocument.Create("generated.xlsx", SpreadsheetDocumentType.Workbook))
{
//Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadSheetDocument.AddWorkbookPart();
//create new workbook
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
//instantiate new worksheet with new sheetdata
worksheetPart.Worksheet = new Worksheet(new SheetData());
//Add Sheets to the Workbook.
Sheets sheets = spreadSheetDocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
DocumentFormat.OpenXml.UInt32Value sheetId = 1;
//Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet();
sheet.Id = spreadSheetDocument.WorkbookPart.GetIdOfPart(worksheetPart);
sheet.SheetId = sheetId;
sheet.Name = new StringValue("test_" + 1);
sheets.Append(sheet);
//Get the sheetData cell table.
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
UInt32Value rowindex = 1;
UInt32Value rowindex2 = 2;
// Add a row to the cell table.
Row row = new Row() { RowIndex = rowindex };
Cell newCell = new Cell();
newCell.DataType = CellValues.InlineString;
newCell.CellReference = "A1";
InlineString inlineString = new InlineString();
Text t = new Text();
t.Text = "test";
inlineString.Append(t);
newCell.AppendChild(inlineString);
row.AppendChild(newCell);
sheetData.AppendChild(row);
rowindex++;
// Add a row to the cell table.
Row row2 = new Row() { RowIndex = rowindex2 };
Cell newCell2 = new Cell();
newCell2.DataType = CellValues.InlineString;
newCell2.CellReference = "A1";
InlineString inlineString2 = new InlineString();
Text t2 = new Text();
t2.Text = "test";
inlineString2.Append(t2);
newCell2.AppendChild(inlineString2);
row2.AppendChild(newCell2);
sheetData.AppendChild(row2);
workbookpart.Workbook.Save();
// Close the document.
spreadSheetDocument.Close();
MessageBox.Show("Success");
}