Reputation: 525
I want to create an excel document based on a template using Open XML Format SDK 2.0. I have followed this tutorial Creating Documents by Using the Open XML Format SDK 2.0 CT. My problem is that the rows and cells i put in to the document doesn't get saved. When I open the document it looks just like the template.
There is no exceptions thrown when I run my code. I figure I have to force the changes to be saved in the document, but I cant figure out how.
Here's some of my code:
public static void GenerateExcelReportToDisk()
{
var factory = new Factory();
var generated = "result.xlsx";
var newFile = Util.GetReportTargetPath() + generated;
var templateFile = Util.GetReportTemplatePath() + @"template.xlsx";
File.Copy(templateFile, newFile, true);
using (var myWorkbook = SpreadsheetDocument.Open(newFile, true))
{
var workbookPart = myWorkbook.WorkbookPart;
var worksheetPart = workbookPart.WorksheetParts.First();
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
//Get data
var data = factory.GetAllFixtures().Take(20);
int rowIndex = 3;
foreach (var fixture in data)
{
var pcRate = fixture.PCRate;
var account = fixture.Charter != null ? fixture.Charter.Shortname : null;
var region = fixture.Region != null ? fixture.Region.GroupName : null;
//CreateContentRow is exactly like the tutorial linked above.
var row = CreateContetRow(rowIndex, region, pcRate, account);
rowIndex++;
sheetData.AppendChild(row);
}
//Tried to add myWorkbook.WorkbookPart.Workbook.Save(); here, but it doesn't do anything
myWorkbook.Close();
}
Upvotes: 1
Views: 1790
Reputation: 525
Well, I managed to figure this out by myself after a short while. Posting the answer here in case it will help someone (including myself):
In the line above myWorkbook.Close();
add worksheetPart.Worksheet.Save();
As simple as that...
Upvotes: 4