[英]Excel Open XML error: “found unreadable content” when creating simple example
[英]Inserting WorkSheet with Open XML - “…unreadable content…”
當我按照本教程進行操作時:
http://msdn.microsoft.com/en-us/library/cc881781.aspx
打開Excel文檔並插入一個空的工作表,最終結果是一條消息,提示“ Excel在...中發現了不可讀的內容?您要恢復此工作簿的內容...”。 如果我恢復了所有插入的工作表都是空白的(即使我以編程方式添加了內容)
將xlsx重命名為.zip並進行檢查后,表明已創建工作表並添加了內容。
任何有類似問題的人嗎? 可能是在新創建的零件之間未建立關系的情況下...
該錯誤消息表示組成您的excel文檔的XML不符合XML Schema,並且無效。 您可以使用Open XML SDK 2.0生產率工具查看問題所在。
我還從鏈接底部復制了代碼,並使它像Chris在他的評論中所說的那樣起作用。 您的代碼如下嗎?
// 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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.