简体   繁体   中英

Document not saving when Created Using the Open XML Format SDK 2.0 CTP

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();
        }

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM