我正在尝试使用Open XML创建文件,但在尝试仅添加第一行标头时,文件已损坏,无法打开,有人能告诉我哪里做错了吗?
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create("C:\\testpdfs\\mytest.xlsx", SpreadsheetDocumentType.Workbook))
{
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = 1,
Name = ViewBag.Title
};
Row row = new Row() { RowIndex = 1 };
Cell header1 = new Cell() { CellReference = "A1", CellValue = new CellValue("Interval Period Timestamp") };
row.Append(header1);
Cell header2 = new Cell() { CellReference = "A2", CellValue = new CellValue("Settlement Interval") };
row.Append(header2);
Cell header3 = new Cell() { CellReference = "A3", CellValue = new CellValue("Aggregated Consumption Factor") };
row.Append(header3);
Cell header4 = new Cell() { CellReference = "A4", CellValue = new CellValue("Loss Adjusted Aggregated Consumption") };
row.Append(header4);
sheet.Append(row);
sheets.Append(sheet);
//sheet.Append(row);
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
return View();
}
1条答案
按热度按时间zed5wv101#
你这里有一些问题。
首先,你要把
row
添加到Sheet
中,但它需要被添加到SheetData
中。最简单的方法是保留对SheetData
对象的引用,以便我们以后使用它:其次,需要为每个单元格显式给予数据类型,因为如果没有指定数据类型,则默认值为number:
最后,单元格引用不完全正确。您将所有内容添加到一行,但添加了对第1到4行的引用(A1-A4)。假设单元格在代码中被称为“标题”,我猜您实际上需要单元格A1-D1中的值,在这种情况下,您只需要更新
CellReference
值。如果您实际上需要A1-A4中的值,那么您可以'我需要将每个单元格添加到一个新行。完整的程式码清单(假设您需要储存格A1-D1)为: