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

如何用OpenXLSX读取XLSX文件中的浮点数?

解决OpenXLSX读取Excel浮点数报错的问题

问题原因

你遇到的XLValueTypeError是因为OpenXLSX严格匹配Excel单元格的实际存储类型与你请求的类型。第三列的单元格可能不是以Float类型存储的——比如它可能是文本格式的数字,或者是整数类型(即使显示为小数),直接调用get<double>()就会触发类型不匹配错误。

解决方案

1. 先确认单元格的实际类型

先通过type()方法查看单元格的存储类型,明确问题所在:

auto cellValue = sheet.cell(fmt::format("C{}", rowIndex)).value();
// 打印类型枚举值,对应XLValueType的枚举(Integer=0, Float=1, String=2等)
std::cout << "当前单元格类型:" << static_cast<int>(cellValue.type()) << std::endl;

2. 根据实际类型处理转换

  • 如果是字符串类型(文本格式的数字):
    先读取为字符串,再转换为double:

    const std::string cellStr = sheet.cell(fmt::format("C{}", rowIndex)).value().get<std::string>();
    const double sdf = std::stod(cellStr);
    
  • 如果是整数类型(比如单元格值是10.0但存储为整数):
    先读取为int,再强制转换为double:

    const int intVal = sheet.cell(fmt::format("C{}", rowIndex)).value().get<int>();
    const double sdf = static_cast<double>(intVal);
    

3. 兼容多种类型的鲁棒写法

如果不确定单元格的存储类型,可以用异常捕获来尝试多种转换方式:

double sdf = 0.0;
auto cellValue = sheet.cell(fmt::format("C{}", rowIndex)).value();

try {
    sdf = cellValue.get<double>();
} catch (const OpenXLSX::XLValueTypeError&) {
    try {
        sdf = static_cast<double>(cellValue.get<int>());
    } catch (const OpenXLSX::XLValueTypeError&) {
        std::string strVal = cellValue.get<std::string>();
        sdf = std::stod(strVal);
    }
}

内容的提问来源于stack exchange,提问作者skrat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 23:32:05