如何使用OPEN XML SDK在C#中格式化打开XML十进制值

时间:2016-04-11 08:38:55

标签: c# asp.net-mvc openxml-sdk

我在MVC应用程序中有一个场景,我使用OPEN XML作为真正的excel文件,然后在表视图中显示列表,精度点的十进制值不能正确读取和格式化,我尝试过多次转换但是好像不行。我试图将其格式化为2位小数,我尝试使用Math.Round,但它似乎不起作用。请参阅下面的代码:这是我的Excel工作表中的Total Claim列值。

private static CleanSupplierClaim MappExcelOpenXMLtoGenericList(IList<string> rowData, IList<string> columnNames)
    {

        var cleanSupplierClaims = new CleanSupplierClaim()
        {
            Action = rowData[columnNames.IndexFor("Action")],
            Line_Number = rowData[columnNames.IndexFor("Lineno")],
            Total_Claim = rowData[columnNames.IndexFor("TotalClaim")].ToDecimalNullable(), //Convert.ToDecimal(Math.Round(Convert.ToDouble(rowData[columnNames.IndexFor("TotalClaim")].ToDoubleNullable()),2)),

            Currency = rowData[columnNames.IndexFor("Currency")],
            ClaimReference = rowData[columnNames.IndexFor("ClaimReference")]
        };

        return cleanSupplierClaims;
    }

这是我读取单元格值的通用类:

    private static string GetCellValue(SpreadsheetDocument document, Cell cell)
{
    if (cell == null) return null;
    string value = cell.InnerText;

    //Process values particularly for those data types.
    if (cell.DataType != null)
    {
        switch (cell.DataType.Value)
        {
            //Obtain values from shared string table.
            case CellValues.SharedString:
                var sstPart = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
                value = sstPart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText.Trim();
                break;

            //Optional boolean conversion.
            case CellValues.Boolean:
                var booleanToBit = ConfigurationManager.AppSettings["BooleanToBit"];
                if (booleanToBit != "Y")
                {
                    value = value == "0" ? "FALSE" : "TRUE";
                }
                break;

            case CellValues.Number:
                return Convert.ToDecimal(cell.CellValue.Text).ToString();
            default:
                if (cell.CellValue != null)
                    return cell.CellValue.Text;
                return string.Empty;

        }
    }
    return value;
}

我尝试过的所有格式都会跳过带小数的值,或者将值返回0,它对整数运行正常,请协助。

这是在使用VS 2013和OPEN XML

的MVC应用程序中

0 个答案:

没有答案