修复记录:来自/xl/styles.xml部分(样式)的格式
为什么要修理我不能得到它?
m_objSpreadsheetDocument = SpreadsheetDocument.Create(FileName, SpreadsheetDocumentType.Workbook);
m_objWorkbookPart = m_objSpreadsheetDocument.AddWorkbookPart();
m_objWorkbookPart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
m_objWorksheetPart = m_objWorkbookPart.AddNewPart<WorksheetPart>();
m_objWorksheetPart.Worksheet = new Worksheet(new SheetData());
m_objWorksheet = m_objWorksheetPart.Worksheet;
// Add Sheets to the Workbook.
Sheets sheets = m_objSpreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = m_objSpreadsheetDocument.WorkbookPart.GetIdOfPart(m_objWorksheetPart),
SheetId = 1,
Name = _sheetName
};
sheets.Append(sheet);
wStylePart = m_objSpreadsheetDocument.WorkbookPart.AddNewPart<WorkbookStylesPart>();
m_objSheetData = m_objWorksheetPart.Worksheet.GetFirstChild<SheetData>();
答案 0 :(得分:0)
如果没有设置WorkbookStylesPart
,则无法Stylesheet
。您需要删除该行
wStylePart = m_objSpreadsheetDocument.WorkbookPart.AddNewPart<WorkbookStylesPart>();
或者您可以设置其StyleSheet
属性:
var wStylePart = m_objSpreadsheetDocument.WorkbookPart.AddNewPart<WorkbookStylesPart>();
wStylePart.Stylesheet = new Stylesheet();
修改强>
您还需要致电Close
上的SpreadsheetDocument
。您可以在代码底部添加对m_objSpreadsheetDocument.Close();
的调用,或者最好在SpreadsheetDocument.Create
语句中将调用包装到using
。
完整的代码将如下所示:
using (var m_objSpreadsheetDocument = SpreadsheetDocument.Create(file, SpreadsheetDocumentType.Workbook))
{
var m_objWorkbookPart = m_objSpreadsheetDocument.AddWorkbookPart();
m_objWorkbookPart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
var m_objWorksheetPart = m_objWorkbookPart.AddNewPart<WorksheetPart>();
m_objWorksheetPart.Worksheet = new Worksheet(new SheetData());
var m_objWorksheet = m_objWorksheetPart.Worksheet;
// Add Sheets to the Workbook.
Sheets sheets = m_objSpreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = m_objSpreadsheetDocument.WorkbookPart.GetIdOfPart(m_objWorksheetPart),
SheetId = 1,
Name = "Sheet 1"
};
sheets.Append(sheet);
//either both of these lines are required or neither of them; you can't add the WorkbookStylesPart alone
var wStylePart = m_objSpreadsheetDocument.WorkbookPart.AddNewPart<WorkbookStylesPart>();
wStylePart.Stylesheet = new Stylesheet();
var m_objSheetData = m_objWorksheetPart.Worksheet.GetFirstChild<SheetData>();
}