Search code examples
c#.netopenxmlopenxml-sdk

Excel create named sheets with populated data


I have been trying to get this to work for almost 3 weeks. The code is suppose to create an excel document with a new named sheet for each item, transfer the object data to the sheet. Unfortunately it is duplicating the data into all of the sheets.

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

Solution

  • Create a workbook (in Excel) that has the three sheets you want. Put a little bit of data on each sheet. Save and close the workbook.

    Open the Open XML SDK Productivity Tool (downloadable from Microsoft's site). Open your new workbook in the tool. Use the Reflect Code button to open the OpenXML code that represents your document.

    Copy/paste the code you need. It's the easiest to get something like this to work. Good luck.