gpt4 book ai didi

c# - 使用 Open XML 插入工作表 - "...unreadable content..."

转载 作者:太空狗 更新时间:2023-10-30 00:46:00 24 4
gpt4 key购买 nike

当我学习本教程时:

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

打开一个 Excel 文档并插入一个空工作表,最终结果是一条消息,提示“Excel 在...中发现不可读的内容,是否要恢复此工作簿的内容...”。如果我恢复所有插入的工作表都是空白的(即使我以编程方式添加内容)

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

有人有类似的问题吗?这可能是因为没有在新创建的部分之间创建关系......

最佳答案

该错误消息表示构成您的 Excel 文档的 XML 不符合 XML 架构并且无效。您可以使用 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);
}
}

关于c# - 使用 Open XML 插入工作表 - "...unreadable content...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4316282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com