我必须创建一个大的XLSX文件。我使用OpenXmlWriter尽快完成任务。 该文件正确创建,但我无法更改该字段的数据类型。它总是标准类型,我想为其中一些使用数字格式。
我尝试了很多方法,但没有人工作(Cell DataType,带有属性,......)。
以下是一个例子:
SpreadsheetDocument fichier_excel = SpreadsheetDocument.Create(chemin + NomFichier, SpreadsheetDocumentType.Workbook);
fichier_excel.AddWorkbookPart();
WorksheetPart wsp = fichier_excel.WorkbookPart.AddNewPart<WorksheetPart>();
OpenXmlWriter writer = OpenXmlWriter.Create(wsp);
writer.WriteStartElement(new Worksheet());
writer.WriteStartElement(new SheetData());
oxa = new List<OpenXmlAttribute>();
oxa.Add(new OpenXmlAttribute("r", null, "1"));
writer.WriteStartElement(new Row(), oxa);
oxa = new List<OpenXmlAttribute>();
oxa.Add(new OpenXmlAttribute("t", null, "str"));
writer.WriteStartElement(new Cell(), oxa);
writer.WriteElement(new CellValue("10001"));
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.Close();
writer = OpenXmlWriter.Create(fichier_excel.WorkbookPart);
writer.WriteStartElement(new Workbook());
writer.WriteStartElement(new Sheets());
writer.WriteElement(new Sheet()
{
Name = "Inventaire",
SheetId = 1,
Id = fichier_excel.WorkbookPart.GetIdOfPart(wsp)
});
writer.WriteEndElement();
writer.WriteEndElement();
writer.Close();
writer.Dispose();
fichier_excel.Close();
fichier_excel.Dispose();
答案 0 :(得分:2)
对于使用号码类型,设置DataType
对象的Cell
属性。
Cell cell = new Cell();
cell.DataType = CellValues.Number;
cell.CellValue = new CellValue("100");
您还需要评论下一行:
oxa.Add(new OpenXmlAttribute("t", null, "str"));
我也是 newCell.StyleIndex = numberIndexStyle;
要获得正确的显示和格式编号,您需要描述cellformat和numberformat:
uint iExcelIndex = 164;
NumberingFormat nformatForcedText = new NumberingFormat
{
NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++),
FormatCode = StringValue.FromString("0.00E+00 ")
};
CellFormat cellFormat1 = new CellFormat()
{
NumberFormatId = 165U,
ApplyNumberFormat = true
};
NumberingFormats numberingFormats = new NumberingFormats();
numberingFormats.Append(nformatForcedText);
numberingFormats.Count = UInt32Value.FromUInt32( (uint)numberingFormats.ChildElements.Count);
CellFormats cellFormats1 = new CellFormats() {};
cellFormats1.Append(cellFormat1 );
cellFormats1.Count = UInt32Value.ToUInt32((uint) cellFormats1.ChildElements.Count);
Stylesheet StyleSheet = new Stylesheet();
StyleSheet.Append(cellFormats1);
StyleSheet.Append(numberingFormats);
WorkbookStylesPart stylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = StyleSheet;
stylesPart.Stylesheet.Save();