我需要使用Open XML使用日期类型在单元格中编写日期。 你能告诉我我该怎么办?
答案 0 :(得分:2)
我得到了答案,并与大家分享......
只需像我们一样添加单元格。
Cell cell =new Cell(){ cellReference=A1 }; //Or other necessary details
cell.cellValue = new CellValue(DateTime.Now.ToOADate().ToString());
cell.StyleIndex=5;
我在这里用过
cell.StyleIndex=5;
这是Excel中日期的默认样式索引。所以不需要添加所有外部styylesheets
享受:)
答案 1 :(得分:1)
因此无需添加所有外部样式表
如果没有样式表我就无法工作。
我用This Blog post让它运转起来。除了使用日期所需的CellStyleFormat和CellFormat部分之外,样式表还需要Font,Border,Fill,DifferentialFormat和TableStyle部分。
private static Stylesheet CreateStylesheet()
{
Stylesheet ss = new Stylesheet();
Fonts fonts = new Fonts(new OpenXmlElement[]
{
new Font
{
FontName = new FontName { Val = "Calibri" },
FontSize = new FontSize { Val = 11 }
}
});
fonts.Count = (uint)fonts.ChildElements.Count;
Fills fills = new Fills(new OpenXmlElement[]
{
new Fill
{
PatternFill = new PatternFill { PatternType = PatternValues.None }
}
});
fills.Count = (uint)fills.ChildElements.Count;
Borders borders = new Borders(new OpenXmlElement[]
{
new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder(),
}
});
borders.Count = (uint)borders.ChildElements.Count;
CellStyleFormats csfs = new CellStyleFormats(new OpenXmlElement[]
{
new CellFormat
{
NumberFormatId = 0,
FontId = 0,
FillId = 0,
BorderId = 0,
}
});
csfs.Count = (uint)csfs.ChildElements.Count;
CellFormats cfs = new CellFormats(new OpenXmlElement[]
{
new CellFormat
{
NumberFormatId = 0,
FontId = 0,
FillId = 0,
BorderId = 0,
FormatId = 0,
},
new CellFormat
{
NumberFormatId = 14,
FontId = 0,
FillId = 0,
BorderId = 0,
FormatId = 0,
ApplyNumberFormat = true
}
});
cfs.Count = (uint)cfs.ChildElements.Count;
ss.Append(fonts);
ss.Append(fills);
ss.Append(borders);
ss.Append(csfs);
ss.Append(cfs);
DifferentialFormats dfs = new DifferentialFormats();
dfs.Count = 0;
ss.Append(dfs);
TableStyles tss = new TableStyles();
tss.Count = 0;
tss.DefaultTableStyle = "TableStyleMedium9";
tss.DefaultPivotStyle = "PivotStyleLight16";
ss.Append(tss);
return ss;
}
样式表到位后,您可以设置StyleIndex。
cell.StyleIndex=14