Changing DataType of cell to Double

笑着哭i 提交于 2019-12-01 23:21:42

Using CellValues.Number works fine for me, for example :

double? value = 4.9874567891;
Cell cell2 = new Cell()
{
    CellReference = "A2",
    DataType = CellValues.Number,
    CellValue = new CellValue(Convert.ToString(value))
};

Double value printed to excel without the warning you got.

Mister B.

I had the same problem. I followed the advices from the various posts and answers applying a style on the cell... no success.

Finally I found the origin of the problem and so the solution :

In my loop, I inserted all data in the same way i.e. using the InsertSharedStringItem() function.

If you insert a number in your spreadsheet like that, the cell formating will be useless and your number will not be considered as a number.

What you should do is to insert it "directly".


index =InsertSharedStringItem(myStringNumber, shareStringPart);
cell = InsertCellInWorksheet("A", 1, worksheetPart);
cell.CellValue = new CellValue(index.ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = _doubleStyleId;

will not work.


cell = InsertCellInWorksheet("A", 1, worksheetPart);
cell.CellValue = new CellValue(myStringNumber);
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
cell.StyleIndex = _doubleStyleId;

is OK

with as Claies wrote :

Stylesheet styleSheet = workbook.WorkbookStylesPart.Stylesheet; 
_doubleStyleId = createCellFormat(styleSheet, null,null, UInt32Value.FromUInt32(4));

the code for createCellFormat() can be found here

OpenXML always creates a cell as Inline Text, and relies upon formatting to determine the correct display format within Excel. Each number format in Excel corresponds to a unique code, and a style can be applied to the cell, the same way you might change the style from within Excel.

The OpenXML Standard defines a series of codes which can be assigned without creating a custom StyleSheet.

The implied format for a double is 4 #,##0.00

so first you create the styleId:

Stylesheet styleSheet = workbook.WorkbookStylesPart.Stylesheet; 
_doubleStyleId = createCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(4));

then, set the styleId on the cell:

cell.StyleIndex = _doubleStyleId;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!