You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用GetCell获取字符串以外的Excel数据类型(int、float等)

解决Excel读取强类型数据问题

要从Excel中读取int、float等强类型数据,不能直接统一用ToString()转换,需要根据NPOI单元格的CellType判断类型后调用对应方法取值,同时要处理空单元格避免空引用异常。

修改步骤说明

  1. 定义辅助方法,分别处理不同类型的单元格值读取,兼容空单元格和多种类型的单元格(比如数值型、字符串型的数字)
  2. 在循环创建VMProduto实例时,调用对应辅助方法获取强类型值
  3. 确保VMProduto的字段类型与读取的类型匹配(比如id_Item设为int或int?,preco_por设为float或float?)

修改后完整代码

[HttpPost]
public IActionResult MostrarDados([FromForm] IFormFile ArquivoExcel)
{
    using Stream stream = ArquivoExcel.OpenReadStream();
    IWorkbook MeuExcel = Path.GetExtension(ArquivoExcel.FileName) == ".xlsx" 
        ? new XSSFWorkbook(stream) 
        : new HSSFWorkbook(stream);

    ISheet HojaExcel = MeuExcel.GetSheetAt(0);
    int cantidadFilas = HojaExcel.LastRowNum;
    List<VMProduto> lista = new List<VMProduto>();

    for (int i = 1; i <= cantidadFilas; i++)
    {
        IRow fila = HojaExcel.GetRow(i);
        if (fila == null) continue; // 跳过空行

        lista.Add(new VMProduto
        {
            id_Item = GetIntValue(fila.GetCell(0)) ?? 0,
            nome_Item = GetStringValue(fila.GetCell(1)),
            qtd_Estoque = GetIntValue(fila.GetCell(2)) ?? 0,
            preco_por = GetFloatValue(fila.GetCell(3)) ?? 0.0f
        });
    } 

    return Ok(lista);
}

// 辅助方法:读取int类型值,兼容空单元格和字符串型数字
private int? GetIntValue(ICell cell)
{
    if (cell == null || cell.CellType == CellType.Blank)
        return null;
    
    return cell.CellType switch
    {
        CellType.Numeric => (int)cell.NumericCellValue,
        CellType.String => int.TryParse(cell.StringCellValue, out var result) ? result : null,
        _ => null
    };
}

// 辅助方法:读取float类型值,兼容空单元格和字符串型数字
private float? GetFloatValue(ICell cell)
{
    if (cell == null || cell.CellType == CellType.Blank)
        return null;
    
    return cell.CellType switch
    {
        CellType.Numeric => (float)cell.NumericCellValue,
        CellType.String => float.TryParse(cell.StringCellValue, out var result) ? result : null,
        _ => null
    };
}

// 辅助方法:读取字符串类型值
private string GetStringValue(ICell cell)
{
    if (cell == null || cell.CellType == CellType.Blank)
        return string.Empty;
    
    return cell.CellType switch
    {
        CellType.String => cell.StringCellValue,
        CellType.Numeric => cell.NumericCellValue.ToString(),
        _ => cell.ToString()
    };
}

关键细节

  • 用using包裹Stream,确保资源自动释放
  • 增加空行判断,跳过Excel中的空行
  • 辅助方法处理了多种单元格类型,比如有些Excel中数字可能以字符串格式存储,通过TryParse兼容这种情况
  • 如果VMProduto的字段允许为空,可以直接返回int?/float?类型,不需要?? 0这类默认值

内容的提问来源于stack exchange,提问作者VICTOR MARCONI SANTOS DE OLIVE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 13:03:23