使用Open XML插入WorkSheet - “......不可读的内容......”

时间:2010-11-30 16:53:41

标签: c# excel openxml openxml-sdk

当我按照本教程学习时:

http://msdn.microsoft.com/en-us/library/cc881781.aspx

打开Excel文档并插入一个空工作表,最终结果是一条消息告诉“Excel找到了不可读的内容......你想要恢复这个工作簿的内容......”。如果我恢复所有插入的工作表都是空白的(即使我以编程方式添加内容)

将xlsx重命名为.zip并检查后,表明已创建工作表,并添加了内容。

有类似问题的人吗?它可能是在新创建的零件之间没有创建关系的东西......

1 个答案:

答案 0 :(得分:7)

该错误消息表示构成excel文档的XML不符合XML Schema且无效。您可以使用Open XML SDK 2.0 Productivity Tool查看问题所在的位置。

我还复制了你链接底部的代码,让它像克里斯在评论中所说的那样工作。你的代码在下面看起来像这样吗?

// Open the document for editing.
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true)) 
{
    // Add a blank WorksheetPart.
    WorksheetPart newWorksheetPart = 
       spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
    newWorksheetPart.Worksheet = new Worksheet(new SheetData());

    Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
    string relationshipId = 
       spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);
    // Get a unique ID for the new worksheet.
    uint sheetId = 1;
    if (sheets.Elements<Sheet>().Count() > 0)
    {
        sheetId = 
        sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
    }

    // Give the new worksheet a name.
    string sheetName = "Sheet" + sheetId;

    // Append the new worksheet and associate it with the workbook.
    Sheet sheet = new Sheet() 
    { Id = relationshipId, SheetId = sheetId, Name = sheetName };
    sheets.Append(sheet);

    string docName = @"C:\Users\Public\Documents\Sheet7.xlsx";
    InsertWorksheet(docName);
}

// Given a document name, inserts a new worksheet.
public static void InsertWorksheet(string docName)
{
    // Open the document for editing.
    using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
    {
        // Add a blank WorksheetPart.
        WorksheetPart newWorksheetPart = spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
        newWorksheetPart.Worksheet = new Worksheet(new SheetData());

        Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
        string relationshipId = spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);

        // Get a unique ID for the new worksheet.
        uint sheetId = 1;
        if (sheets.Elements<Sheet>().Count() > 0)
        {
            sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
        }

        // Give the new worksheet a name.
        string sheetName = "Sheet" + sheetId;

        // Append the new worksheet and associate it with the workbook.
        Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
        sheets.Append(sheet);
    }
}