经过多次反复试验,我发现样式表需要以下内容:
忽略其中任何一个都会导致 Excel 出错,除非所有这些都被忽略。此外,我为日期添加了另一种单元格格式。
我希望这对其他人有用。以下代码创建了一个允许日期格式(数字格式 id 22)的工作样式表:
var stylesheet = new Stylesheet();
// Default Font
var fonts = new Fonts() { Count = 1, KnownFonts = BooleanValue.FromBoolean(true) };
var font = new Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) }
};
fonts.Append(font);
stylesheet.Append(fonts);
// Default Fill
var fills = new Fills() { Count = 1 };
var fill = new Fill();
fill.PatternFill = new PatternFill() { PatternType = new EnumValue<PatternValues>(PatternValues.None) };
fills.Append(fill);
stylesheet.Append(fills);
// Default Border
var borders = new Borders() { Count = 1 };
var border = new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
};
borders.Append(border);
stylesheet.Append(borders);
// Default cell format and a date cell format
var cellFormats = new CellFormats() { Count = 2 };
var cellFormatDefault = new CellFormat { NumberFormatId = 0, FormatId = 0, FontId = 0, BorderId = 0, FillId = 0 };
cellFormats.Append(cellFormatDefault);
var cellFormatDate = new CellFormat { NumberFormatId = 22, FormatId = 0, FontId = 0, BorderId = 0, FillId = 0, ApplyNumberFormat = BooleanValue.FromBoolean(true) };
cellFormats.Append(cellFormatDate);
stylesheet.Append(cellFormats);
return stylesheet;
生成的 XML 如下所示:
<?xml version="1.0" encoding="utf-8"?>
<x:styleSheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<x:fonts count="1" x14ac:knownFonts="1" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">
<x:font>
<x:sz val="11" />
<x:name val="Calibri" />
<x:family val="2" />
<x:scheme val="minor" />
</x:font>
</x:fonts>
<x:fills count="1">
<x:fill>
<x:patternFill patternType="none" />
</x:fill>
</x:fills>
<x:borders count="1">
<x:border>
<x:left />
<x:right />
<x:top />
<x:bottom />
<x:diagonal />
</x:border>
</x:borders>
<x:cellXfs count="2">
<x:xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" />
<x:xf numFmtId="22" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1" />
</x:cellXfs>
</x:styleSheet>