首页 > 解决方案 > 无法将类型“OfficeOpenXml.ExcelRange”转换为“double?”

问题描述

using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
{
    ExcelWorksheet sheet = excelPackage.Workbook.Worksheets.First();

    for (int rowNum = 2; rowNum <= sheet.Dimension.End.Row; rowNum++)
    {
        var wsRow = sheet.Cells[rowNum, 1, rowNum, sheet.Dimension.End.Column];
        DataRow row = dt.Rows.Add();
        foreach (var cell in wsRow)
        {
            if (wsRow[rowNum, 12] == null)
            {
                break;
            }

            row["model_number"] = wsRow[rowNum, 1];
            row["product_name"] = wsRow[rowNum, 2];
            row["enemy"] = wsRow[rowNum, 9];

            try
            {
                row["regular_price"] = wsRow[rowNum, 3] == null ? DBNull.Value : (double?)wsRow[rowNum, 3] == 0 ? DBNull.Value : wsRow[rowNum, 3];
            }
            catch (Exception)
            {
                row["regular_price"] = 0;
            }                   
        }
    }
}

在写入 excel 的最后一行我得到了错误

无法将类型“OfficeOpenXml.ExcelRange”转换为“double?”

标签: c#excelepplus

解决方案


要获取实际的单元格值,您需要使用如下.Value属性ExcelRange

(double?)wsRow[rowNum, 3].Value == 0

否则,正如错误所解释的那样,您正在尝试将 anExcelRange转换为双精度。

你的其他线路也是如此。喜欢

row["model_number"] = wsRow[rowNum, 1];

你可能真的想要

row["model_number"] = wsRow[rowNum, 1].Value;

除非您确信 excel 中的数据是“干净的”,否则可能需要进行一些类型检查。


推荐阅读