所以我需要将我的应用程序中的一些数据导出到xml文件中,并且我试图通过使用OpenXML来实现这一点,但我正在使用的代码生成aditional(封闭)元素并且它会阻止文件被打开。
<?xml version="1.0" encoding="utf-8"?>
<x:worksheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<x:sheetData /> <---- this guy here.
<x:sheetData>
<x:row><x:c t="str">
<x:v>Key</x:v></x:c>
<x:c t="str"><x:v>Value</x:v></x:c>
</x:row>
</x:sheetData>
</x:worksheet>
这是我用来生成文件的代码。
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(System.IO.Path.Combine(currentPath, "Export Data") + $@"\Export-{DateTime.Now.Year}.xlsx", SpreadsheetDocumentType.Workbook);
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Temp"
};
sheets.Append(sheet);
SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
Row row = new Row();
row.Append(
ConstructCell("Key", CellValues.String),
ConstructCell("Value", CellValues.String));
sheetData.AppendChild(row);
worksheetPart.Worksheet.Save();
spreadsheetDocument.Close();
有谁能告诉我额外的“SheetData”元素来自哪里?我不能仅仅通过观察来判断。
答案 0 :(得分:1)
我太蠢了。在我发布问题之后,我发现我正在创建一个不必要的sheetdata元素
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData()); // HERE