我正在尝试通过打开xml 创建一个带有表格的电子表格。但是当打开创建的excel文件时,它总是返回错误“Excel在test1.xlsx中发现不可读的内容,你想要恢复。为什么总是会发生这个错误?当没有表创建excel时,我没有得到任何错误。请查找下面我用来创建的示例代码。
using (SpreadsheetDocument spreadsheetdocument = SpreadsheetDocument.Create(@"c://test.xlsx", SpreadsheetDocumentType.Workbook))
{
// add a workbookpart to the document.
WorkbookPart workbookpart = spreadsheetdocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// add a worksheetpart to the workbookpart.
WorksheetPart worksheetpart = workbookpart.AddNewPart<WorksheetPart>();
worksheetpart.Worksheet = new Worksheet(new SheetData());
// add sheets to the workbook.
Sheets sheets = spreadsheetdocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
// append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetdocument.WorkbookPart.
GetIdOfPart(worksheetpart),
SheetId = 1,
Name = "mysheet"
};
sheets.Append(sheet);
TableDefinitionPart tableDefinitionPart = worksheetpart.AddNewPart<TableDefinitionPart>("rId1");
GenerateTablePartContent(ref tableDefinitionPart);
TableParts tableParts1 = new TableParts() { Count = (UInt32Value)2U };
TablePart tablePart1 = new TablePart() { Id = "rId1" };
tableParts1.Append(tablePart1);
worksheetpart.Worksheet.Append(tableParts1);
spreadsheetdocument.Close();
}
//Added spaces to get the code in one block
private void GenerateTablePartContent(TableDefinitionPart part)
{
Table table1 = new Table() { Id = (UInt32Value)1U, Name = "Table1", DisplayName = "Table1", Reference = "A1:C3", TotalsRowShown = false };
AutoFilter autoFilter1 = new AutoFilter() { Reference = "A1:C3" };
TableColumns tableColumns1 = new TableColumns() { Count = (UInt32Value)3U };
TableColumn tableColumn1 = new TableColumn() { Id = (UInt32Value)1U, Name = "Column1" };
TableColumn tableColumn2 = new TableColumn() { Id = (UInt32Value)2U, Name = "Column2" };
TableColumn tableColumn3 = new TableColumn() { Id = (UInt32Value)3U, Name = "Column3" };
tableColumns1.Append(tableColumn1);
tableColumns1.Append(tableColumn2);
tableColumns1.Append(tableColumn3);
TableStyleInfo tableStyleInfo1 = new TableStyleInfo() { Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false };
table1.Append(autoFilter1);
table1.Append(tableColumns1);
table1.Append(tableStyleInfo1);
part.Table = table1;
}
答案 0 :(得分:1)
使用Open XML SDK Productivity Tool。使用常规方法创建excel文件并将相同的数据放在那里,并将该文件与您使用代码创建的文件进行比较。你会看到那里的变化。我也面临同样的问题,我正在尝试使用该工具修复更改。让我们看看......
如果您已经解决了问题,请指导我如何操作。