简体   繁体   English

导出到Excel(OpenXML)导致内容不可读

[英]Exporting to Excel (OpenXML) results in Unreadable Content

I've been struggeling with creating worksheets for my xlsx file. 我一直在努力为我的xlsx文件创建工作表。 Adding the first worksheet isn't a problem, but when I want a second sheet, the exported xlsx seems to be corrupt. 添加第一个工作表不是问题,但是当我想要第二个工作表时,导出的xlsx似乎已损坏。 Who can point out to me what I'm doing wrong? 谁能向我指出我做错了什么? Note: I already tried to also call 'workbookpart,Workbook.Save();' 注意:我已经尝试过调用'workbookpart,Workbook.Save();'。 right after creating the first Workbook, but without the required result. 在创建第一个工作簿后立即执行,但没有所需的结果。

protected void export_Click(object sender, EventArgs e)
{
    ExportToExcel(@"D:\dev\Dotnet4\Excel\test.xlsx");
}

private void ExportToExcel(string filepath)
{
    SpreadsheetDocument spreadsheetDocument;
    WorkbookPart workbookpart;
    CreateSpreadsheet(filepath, out spreadsheetDocument, out workbookpart);

    CreateWorksheet(spreadsheetDocument, workbookpart, "My sheet 1");
    CreateWorksheet(spreadsheetDocument, workbookpart, "My sheet 2");

    workbookpart.Workbook.Save();

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

private static void CreateWorksheet(SpreadsheetDocument spreadsheetDocument, WorkbookPart workbookpart, string worksheetName)
{
    // 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());

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

private static void CreateSpreadsheet(string filepath, out SpreadsheetDocument spreadsheetDocument, out WorkbookPart workbookpart)
{
    // Create a spreadsheet document by supplying the filepath.
    // By default, AutoSave = true, Editable = true, and Type = xlsx.
    spreadsheetDocument = SpreadsheetDocument.
        Create(filepath, SpreadsheetDocumentType.Workbook);

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

I think you have 2 small issues: 我认为您有2个小问题:

  1. The SheetId is the same for both sheets you are adding which is invalid. 您要添加的两个工作表的SheetId均相同,但无效。
  2. You are adding a new Sheets element each time you call CreateWorksheet but there should only be one such element in the XML (there are many Sheet 's but not many Sheets !). 每次调用CreateWorksheet时都要添加一个新的Sheets元素,但是XML中应该只有一个这样的元素(有很多Sheet ,但没有Sheets !)。

To solve 1 you could use the count of the sheets.ChildElements . 要解决1,您可以使用sheets.ChildElements的计数。 As this is 0 first time round and one the second you'll need to add 1 to it. 由于第一次是0第二次是0 ,因此您需要将其加1 If you prefer you could take it in to CreateWorksheet as a parameter; 如果愿意,可以将其作为参数CreateWorksheet it doesn't really matter as long as they start at 1 and are different. 只要它们从1开始并且是不同的,它并不重要。

To solve 2 you can perform a null check on the Sheets property of the Workbook and only create it if it doesn't already exist. 要解决2,您可以对WorkbookSheets属性执行空检查,并仅在不存在时才创建它。

The below should do what you're after. 以下应该做的是您要遵循的。

private static void CreateWorksheet(SpreadsheetDocument spreadsheetDocument, WorkbookPart workbookpart, string worksheetName)
{
    // Add a WorksheetPart to the WorkbookPart.
    WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
    worksheetPart.Worksheet = new Worksheet(new SheetData());

    // Add Sheets to the Workbook.
    if (spreadsheetDocument.WorkbookPart.Workbook.Sheets == null)
    {
        //spreadsheetDocument.WorkbookPart.Workbook.Sheets = new Sheets();
        spreadsheetDocument.WorkbookPart.Workbook
                                        .AppendChild<Sheets>(new Sheets());
    }

    Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.Sheets;

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

One final point is that SpreadsheetDocument implements IDisposable so it should be disposed after use. 最后一点是SpreadsheetDocument实现IDisposable因此应在使用后丢弃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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