[英]Read International Currency symbols from excel sheet in java poi 4.1.2
我無法使用 poi 4.1.2 (XSSF) 將國際貨幣和會計編號格式從 Excel 工作表讀取到 java 獨立應用程序中。 只能讀取美國語言環境符號,但無法讀取 java 中的其他貨幣符號。 使用貨幣符號僅某些格式的單元格值顯示在 java DataFormatter 中,其他格式顯示為?(例如:I/P:$10.00 O/P:?10.00)。
會計編號格式無法讀取歐元貨幣符號(例外:非法參數例外)和一些顯示單元格數據的貨幣符號(貨幣符號和值)。 代碼:
for(int i=1;i<=rows;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;
}
}
}
}
例外:
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) 並將 € 符號放置在值之前,例如€ 1,234.56
時, DataFormatter
似乎確實存在錯誤。 所有默認使用歐元的國家通常都不會這樣做。 他們寫的貨幣是1,234.56 €
,所以 € 符號放在價值后面。
如果在Excel
使用使用符號€ Euro (€ 123)
的數字格式貨幣或會計,則Excel
會創建類似[$€-2]\\ #,##0.00
的數字格式。 這意味着貨幣符號 € 放在值前面。 但是apache poi
將2
解釋為國家代碼,如[$£-809]#,##0.00
中的809
表示英國。 因此,由於這種誤解,它失敗了,因為它沒有找到代碼2
的國家/地區。
解決方法可能是將數據格式字符串中的所有“[$\€-2]”替換為“\€”。 那就是用€
符號替換所有[$€-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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.