【问题标题】:Writing in excel file with poi用 poi 在 excel 文件中写入
【发布时间】:2012-10-29 09:35:42
【问题描述】:

我从一个 excel 文件中获取电话号码并使用以下代码写入另一个 excel 文件

cellph = row.getCell(3);
Object phone = cellph.getNumericCellValue();
String strphone = phone.toString();
cellfour.setCellType(cellfour.CELL_TYPE_STRING);
cellfour.setCellValue("0"+strphone);

它将电话号码写为 09.8546586。我想把它写成 098546586(没有精度值)。该怎么做?

【问题讨论】:

  • 你确定“strphone”不包含精度吗?如果单元格类型是数字,Excel 通常会消除前面的 0。你的输出有点连线。
  • cellph.getNumericCellValue(); 将返回 double(这是原始类型。您如何将其存储在 Object 中?
  • 如果单元格是数字单元格getStringCellValue()会抛出异常
  • 我使用了 getStringCellValue() 但它说数值不能在字符串中获取。
  • 您是否有理由不应用包含合适格式字符串的单元格样式?

标签: java apache-poi


【解决方案1】:

您的问题不在于写入。你的问题在于 read,这就是给你浮点数的原因

根据您的代码和说明,您的电话号码似乎以数字单元格的形式存储在 Excel 中,并应用了整数格式。这意味着当您检索单元格时,您将获得一个double 数字,以及一个告诉您如何像 Excel 一样格式化它的单元格格式。

我认为您可能想要做的更像是:

DataFormatter formatter = new DataFormatter();

cellph = row.getCell(3);
String strphone = "(none available)";

if (cellph.getCellType() == Cell.CELL_TYPE_NUMERIC) {
   // Number with a format
   strphone = "0" + formatter.formatCellValue(cellph);
}
if (cellph.getCellType() == Cell.CELL_TYPE_STRING) {
   // String, eg they typed ' before the number
   strphone = "0" + cellph.getStringCellValue();
}
// For all other types, we'll show the none available message

cellfour.setCellType(cellfour.CELL_TYPE_STRING);
cellfour.setCellValue(strphone);

【讨论】:

  • 亲爱的 gagravarr.org, 非常感谢。我得到了输出。再次非常感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多