There really seems to be a bug in DataFormatter
when currency € (EURO) is used with € sign placed in front of the value like € 1,234.56
. All default Euro using states normally don't do so. They are writing currency like 1,234.56 €
, so € sign placed behind the value.
If the Number format Currency or Accounting using symbol € Euro (€ 123)
is used in Excel
, then Excel
creates a number format like [$€-2] #,##0.00
. That means currency symbol € placed in front of the value. But apache poi
interprets that 2
as a country code like in [$£-809]#,##0.00
where the 809
means Great Britain. So because of that misinterpretation it fails since it does not find a country for code 2
.
A workaround could be replacing all "[$u20AC-2]" in data-format string with "u20AC". That is replacing all [$€-2]
with only the €
sign.
Example:
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 + "");
} catch (Exception ex) {
ex.printStackTrace();
}
}
writer.println();
}
writer.close();
workbook.close();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…