【发布时间】:2018-12-07 11:09:03
【问题描述】:
以下是我用来添加新工作表到现有电子表格的代码。
我在输入中传递了一个列表
private static void PutInExcel(List<RulesEngineOutput> output)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Open(@"C:\ATP\Sprints\PA\RE\IO.xlsx", true))
{
// Add a blank WorksheetPart.
WorksheetPart newWorksheetPart = document.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = document.WorkbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = document.WorkbookPart.GetIdOfPart(newWorksheetPart);
// Get a unique ID for the new worksheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
// Give the new worksheet a name.
string sheetName = "NewRole" + sheetId;
// Append the new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
SheetData sheetData = newWorksheetPart.Worksheet.AppendChild(new SheetData());
// Constructing header
Row row = new Row();
row.Append(
ConstructCell("Code", CellValues.String),
ConstructCell("Description", CellValues.String));
// Insert the header row to the Sheet Data
sheetData.AppendChild(row);
foreach (var reItem in output)
{
row = new Row();
row.Append(
ConstructCell(reItem.Code.ToString(), CellValues.Number),
ConstructCell(reItem.Description, CellValues.String)
);
sheetData.AppendChild(row);
}
newWorksheetPart.Worksheet.Save();
document.WorkbookPart.Workbook.Save();
document.Save();
}
}
问题是一切都没有错误发生,我的意思是我可以在调试窗口中看到添加的工作表,我也在保存所有内容,但是当我打开那个 spreadhseet 时,我看到一个错误消息
We found some problem with some content
最后表格显示没有任何内容,如下所示:
【问题讨论】:
标签: c# .net excel openxml worksheet