问题描述
我无法使用 poi 4.1.2 (XSSF) 将国际货币和会计编号格式从 Excel 工作表读取到 java 独立应用程序中。只能读取美国语言环境符号,但无法读取 java 中的其他货币符号。使用货币符号在java DataFormatter中仅显示某些格式的单元格值,其他格式显示为?(例如:I/P:$10.00 O/P:?10.00)。
会计编号格式无法读取欧元货币符号(例外:非法参数异常)和一些显示单元格数据的货币符号(货币符号和值)。 代码:
for(int i=1;i
String ExcelFilename = sheet.getRow(i).getCell(<cell no of file>).getRichStringCellValue().getString().trim();
if(ExcelFilename.equals("<file name>")) {
for(int j=0;j<columns;j++) {
DataFormatter formatter = new DataFormatter();
cell = sheet.getRow(i).getCell(j,Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
String check= "";
switch (cell.getCellType()) {
case BLANK:
check= formatter.formatCellValue(cell);
break;
case NUMERIC:
check= formatter.formatCellValue(cell);
break;
case BOOLEAN:
check =formatter.formatCellValue(cell);
break;
case STRING:
check=formatter.formatCellValue(cell);
break;
case FORMULA:
check= formatter.formatCellValue(cell);
break;
default:
break;
}
}
}
}
异常:
- 100.00 欧元 - 欧元
从 Excel 表会计 -> 货币类型为欧元 -> 运行课程后,我得到以下异常。
org.apache.poi.ss.format.CellFormat 警告:格式无效:“_ [$€-2]\ * #,##0.00_ ;” java.lang.IllegalArgumentException: Unsupported [] format block '[' in '_ [$€-2]\ * #,##0.00_' with c2: null
同样,我也遇到了一些其他会计格式货币符号的例外情况。 输入(Excel工作表)- 输出(Java) - 100
输出应该无一例外地显示在java中并带有单元格数据(符号和数值)。
解决方法
当使用货币 € (EURO) 并在值前放置 € 符号(如 DataFormatter
)时,€ 1,234.56
中似乎确实存在错误。所有默认使用欧元的国家通常都不会这样做。他们写的是像 1,234.56 €
这样的货币,所以 € 符号放在值后面。
如果在 € Euro (€ 123)
中使用数字格式货币或使用符号 Excel
的会计,则 Excel
会创建类似 [$€-2]\ #,##0.00
的数字格式。这意味着货币符号 € 放在值前面。但 apache poi
将 2
解释为国家代码,如 [$£-809]#,##0.00
中的 809
表示英国。因此,由于这种误解,它失败了,因为它没有找到代码 2
的国家。
解决方法可能是将数据格式字符串中的所有“[$\u20AC-2]”替换为“\u20AC”。即仅用 [$€-2]
符号替换所有 €
。
示例:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.PrintWriter;
class ReadExcelUsingDataFormatter {
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("ExcelExample.xlsx"));
DataFormat format = workbook.createDataFormat();
DataFormatter dataFormatter = new DataFormatter();
PrintWriter writer = new PrintWriter("Result.txt","UTF-8");
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
try {
String dataFormatString = cell.getCellStyle().getDataFormatString();
if (dataFormatString.contains("[$\u20AC-2]")) {
System.out.println(dataFormatString);
dataFormatString = dataFormatString.replace("[$\u20AC-2]","\u20AC");
System.out.println(dataFormatString);
cell.getCellStyle().setDataFormat(format.getFormat(dataFormatString));
}
String value = dataFormatter.formatCellValue(cell);
System.out.println(value); //This might not be printed correctly because of unicode deficiency of `System.out`. But `Result.txt` should contain it corrcetly.
writer.print(value + "\t\t");
} catch (Exception ex) {
ex.printStackTrace();
}
}
writer.println();
}
writer.close();
workbook.close();
}
}