我一直在努力使其工作近3周。该代码假定为每个项目创建一个带有新命名工作表的excel文档,并将对象数据传输到工作表。不幸的是,它正在将数据复制到所有工作表中。
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create
(filepath, 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();
// Add Sheets to the Workbook
Sheets sheets = workbookpart.Workbook.
AppendChild(new Sheets());
// Append a new worksheet and associate it with the workbook.
SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
foreach (Town temp in CampaignTowns)
{
// Constructing header
Row row = new Row();
row = CreateContentRow(temp, sheetData);
// Insert the header row to the Sheet Data
//sheetData.AppendChild(row);
Sheet sheet = new Sheet()
{
Id = workbookpart.GetIdOfPart(worksheetPart),
SheetId = TempSheetId,
Name = temp.getName()
};
TempSheetId++;
sheets.Append(sheet);
sheetData = new SheetData();
}
//Save worksheet part
worksheetPart.Worksheet.Save();
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
答案 0 :(得分:0)
创建一个包含三个所需工作表的工作簿(在Excel中)。在每张纸上放一点数据。保存并关闭工作簿。
打开Open XML SDK Productivity Tool
(可从Microsoft网站下载)。在工具中打开您的新工作簿。使用Reflect Code
按钮打开代表您的文档的OpenXML代码。
复制/粘贴所需的代码。最简单的方法就是让这种方法起作用。祝你好运。
答案 1 :(得分:0)
因此,在进行了一些研究之后,我发现了我的错误并进行了纠正。显然,您必须在循环中初始化Worksheet部件和SheetData。这是我的工作更正代码的副本,适用于任何有相同错误的人。我还把我的CreateContentRow函数更正为空。
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create
(filepath, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add Sheets to the Workbook
Sheets sheets = workbookpart.Workbook.
AppendChild(new Sheets());
foreach (Town temp in CampaignTowns)
{
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
worksheetPart.Worksheet.Save();
// Append a new worksheet and associate it with the workbook.
SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
// Insert the header row to the Sheet Data
CreateContentRow(temp, sheetData);
Sheet sheet = new Sheet()
{
Id = workbookpart.GetIdOfPart(worksheetPart),
SheetId = TempSheetId,
Name = temp.getName()
};
TempSheetId++;
sheets.AppendChild(sheet);
}
// Close the document.
spreadsheetDocument.Close();