用Open XML插入WorkSheet – “…不可读的内容…”
当我按照这个教程:
http://msdn.microsoft.com/en-us/library/cc881781.aspx
打开一个Excel文档并插入一个空的工作表,最后的结果是一条消息,告诉“Excel中发现不可读的内容…是否要恢复此工作簿的内容…”。 如果我恢复所有插入的工作表是空白的(即使我编程添加内容)
将xlsx重命名为.zip并检查后,显示工作表已创build,并添加了内容。
任何有类似问题的人? 这可能是不创build新创build的部分之间的关系的东西…
该错误消息意味着组成您的Excel文档的XML不符合XML Schema并且是无效的。 您可以使用Open XML SDK 2.0生产力工具来查看问题的位置。
我也复制了链接底部的代码,并像克里斯在评论中所说的那样使它工作。 你的代码是否如下所示?
// 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); } }