如何用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
相关产品推荐
相关产品推荐

