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

如何使用Java读取CSV/Excel文件中科学计数法存储的原始整数值

还原Java读取Excel/CSV时的科学计数法为原始整数

核心问题原因

长整数在Excel/CSV中被自动转为科学计数法显示,读取时若按数值类型处理会得到近似的科学计数法字符串,需通过精确类型转换还原。


解决方案

1. Excel文件处理(Apache POI)

使用Apache POI读取时,通过BigDecimal转换数值型单元格,避免精度丢失:

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import java.math.BigDecimal;

public String getOriginalIntegerFromCell(Cell cell) {
    if (cell.getCellType() == CellType.NUMERIC) {
        // 用BigDecimal精确转换数值,转为无科学计数法的字符串
        return new BigDecimal(cell.getNumericCellValue()).toPlainString();
    }
    // 文本类型直接返回
    return cell.getStringCellValue();
}

关键:存储长整数时,将Excel单元格设置为文本格式,可彻底避免自动转为科学计数法。

2. CSV文件处理

读取CSV时优先按字符串解析,避免数值转换:

  • 原生BufferedReader读取:
import java.io.BufferedReader;
import java.io.FileReader;

public void readCsvAsText(String filePath) throws Exception {
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        String line;
        while ((line = br.readLine()) != null) {
            String[] columns = line.split(",");
            // 直接获取对应列的字符串值
            String originalValue = columns[0]; // 假设目标值在第一列
            System.out.println(originalValue);
        }
    }
}
  • OpenCSV库读取:
import com.opencsv.CSVReader;
import java.io.FileReader;

public void readCsvWithOpenCsv(String filePath) throws Exception {
    try (CSVReader reader = new CSVReader(new FileReader(filePath))) {
        String[] row;
        while ((row = reader.readNext()) != null) {
            String originalValue = row[0];
            System.out.println(originalValue);
        }
    }
}

3. 已获取科学计数法字符串的转换

如果已经拿到了"1.54489E+15"这类字符串,直接用BigDecimal转换:

import java.math.BigDecimal;

public String convertSciToInteger(String sciNotationStr) {
    return new BigDecimal(sciNotationStr).toPlainString();
}

重要提示:若Excel在存储时已将原始长整数近似为科学计数法(丢失了末尾精度),则无法完全还原原始值。因此提前将单元格设为文本格式存储长整数是最优方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 09:40:18