创建多个Excel电子表格

时间:2014-06-16 06:12:53

标签: c# openxml openxml-sdk

我使用以下代码

// Create a spreadsheet document
            SpreadsheetDocument spreadsheetDocument  = SpreadsheetDocument.Create(excelLocation + @"\example1.xlsx", 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(new SheetData());
            // Add Sheets to the Workbook.
            Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
            UInt32Value sheetCount = 0;

            foreach (string value in Holder.country) 
            {
                // Append a new worksheet and associate it with the workbook.

                Sheet sheet = new Sheet() { 
                    Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), 
                    SheetId = sheetCount, 
                    Name = value
                };
                sheets.Append(sheet);
                sheetCount++;
            }


            workbookpart.Workbook.Save();

            // Close the document.
            spreadsheetDocument.Close();

但它总是告诉我

  

Excel在&#34; example1.xlsx&#34;中找到了不可读的内容。你想恢复这个工作簿的内容吗? ......

我在互联网上阅读了一些内容,他们说这是由于sheetCount。这有多大可能,因为我在每个循环中添加了1个。

1 个答案:

答案 0 :(得分:3)

这里有些混乱。

  • 您需要为自己创建的每个工作表添加worksheetpart。在这里,你 所有工作表仅参考一个worksheetpart
  • sheetId的最小值为 1 ,而不是 0

// Create a spreadsheet document
SpreadsheetDocument spreadsheetDocument  = SpreadsheetDocument.Create(excelLocation + @"\example1.xlsx", SpreadsheetDocumentType.Workbook);

// Add a WorkbookPart to the document
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();

// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

UInt32Value sheetCount = 1; // Mimimum value is 1

foreach (string value in Holder.country) 
{

    // Add a WorksheetPart to the WorkbookPart
    WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
    worksheetPart.Worksheet = new Worksheet(new SheetData());

    // Append a new worksheet and associate it with the workbook.
    Sheet sheet = new Sheet() { 
                Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), 
                SheetId = sheetCount, 
                Name = value
            };
    sheets.Append(sheet);
    sheetCount++;
}

workbookpart.Workbook.Save();

// Close the document.
spreadsheetDocument.Close();