【问题标题】:Comma convert to dot after reading xls file with Apache POI使用 Apache POI 读取 xls 文件后逗号转换为点
【发布时间】:2023-03-11 05:48:01
【问题描述】:

我在通过 Apache POI 读取 xls 文件时遇到问题。

test.xls 包含一个一般类型的单元格:123,56。

测试代码:

FileInputStream myxls = new FileInputStream(path);
HSSF myworkbook = new HSSFWorkbook(myxls);
HSSF mysheet = myworkbook.getSheetAt(0);
HSSF myrow = mysheet.getRow(1);
HSSF mycell = myrow.getCell(0);
System.out.Println(mycell.toString()); 

输出:123.56。逗号转换为点,但我想得到结果为 123,56

我尝试使用不同的方法:

mycell.getNumericCellValue(); returns 123.56
mycell.toString(); returns 123.56
mycell.getRichStringCellValue(); returns an exception
mycell.getStringCellValue(); returns an exception 

我尝试使用它:

static DataFormatter dataFormatter = new DataFormatter();

static String getStringValue(Cell cell) {
    return dataFormatter.formatCellValue(cell);
}

但结果相同:123.56

【问题讨论】:

  • 如果单元格是“通用”类型,那么您肯定应该使用“mycell.getStringCellValue()”,这会返回“123,56”。

标签: java apache-poi


【解决方案1】:

该值以数字形式保存,java 中的 toString 转换遵循程序员的带点符号。

Locale locale = new Locale(...);
String repr = String.format(locale, "%.2f", mycell.getNumericCellValue());

喜欢NumberFormat:

NumberFormat format = NumberFormat.getInstance(locale);
String repr = format.format(mycell.getNumericCellValue());

【讨论】:

    【解决方案2】:

    如果你只需要它来输出,那么试试这个:

    mycell.toString().replace(".",",")
    

    或者您可以为您的单元格设置特定样式: Write Double value in numeric cell with specific format in Apache Poi 3.7

    【讨论】:

      猜你喜欢
      • 2013-07-10
      • 2014-07-10
      • 2015-11-25
      • 1970-01-01
      • 2011-06-08
      • 2013-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多