Inserting WorkSheet with Open XML - "...unreadable content..."
When I follow this tutorial:
http://msdn.microsoft.com/en-us/library/cc881781.aspx
to open an Excel document and insert an empty worksheet the final result is a message telling "Excel found unreadable content in ... Do you want to recover the contents of this workbook...". If I recover all the inserted sheets are blank (even if I add content programatically)
After renaming the xlsx to .zip and examining it shows that the worksheets have been created, and content added.
Anyone with any si开发者_运维问答milar problems? It may be something with not creating relationships between newly created parts...
That error message means that the XML that makes up your excel document is not conforming to the XML Schema and is invalid. You can use the Open XML SDK 2.0 Productivity Tool to see where the issue is located.
I also copied the code from the bottom of your link and got it to work like Chris said in his comment. Does your code look like this below?
// 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);
}
}
精彩评论