POI电子表格本地化

时间:2019-06-24 16:56:22

标签: java localization apache-poi

使用Apache POI OOXML和XSSF模式,创建一个新的工作簿,如何设置电子表格的语言(即英语(美国))?我找不到任何东西。该设置不需要特定于单元格,并且应适用于所有工作表。我正在使用POI版本4.1.0。

1 个答案:

答案 0 :(得分:1)

Excel文件中的图纸数据存储未本地化。在功能名称,列表定界符以及十进制和千位定界符方面,工作表数据的存储始终为美国英语。仅Excel应用程序已本地化。 Excel GUI从文件中读取数据,然后转换函数名称,列表定界符以及十进制和数千个定界符。

让我们举个例子:

import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.GregorianCalendar;

class CreateExcel {

 public static void main(String[] args) throws Exception {

  try (Workbook workbook = new XSSFWorkbook(); 
       FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {

   Object[][] data = new Object[][] {
    new Object[] {"Value", "Date", "Formatted value", "Formula"},
    new Object[] {123.456789, new GregorianCalendar(2019, 0, 15), 123.456789, "ROUND(A2,2)"},
    new Object[] {1234.56789, new GregorianCalendar(2019, 5, 15), 1234.56789, "ROUND(A3,2)"}
   };

   DataFormat dataFormat = workbook.createDataFormat();
   CellStyle dateStyle = workbook.createCellStyle();
   dateStyle.setDataFormat(dataFormat.getFormat("DDDD, MMMM, DD, YYYY"));
   CellStyle numberStyle = workbook.createCellStyle();
   numberStyle.setDataFormat(dataFormat.getFormat("#,##0.00 \" Coins\""));

   Sheet sheet = workbook.createSheet(); 

   for (int r = 0; r < data.length; r++) {
    Row row = sheet.createRow(r);
    for (int c = 0; c < data[0].length; c++) {
     Cell cell = row.createCell(c);

     if (r == 0) cell.setCellValue((String)data[r][c]);
     if (r > 0 && c == 0) {
      cell.setCellValue((Double)data[r][c]);
     } else if (r > 0 && c == 1) {
      cell.setCellValue((GregorianCalendar)data[r][c]);
      cell.setCellStyle(dateStyle);
     } else if (r > 0 && c == 2) {
      cell.setCellValue((Double)data[r][c]);
      cell.setCellStyle(numberStyle);
     } else if (r > 0 && c == 3) {
      cell.setCellFormula((String)data[r][c]);
     }
    }
   }

   for (int c = 0; c < data[0].length; c++) {
    sheet.autoSizeColumn(c);
   }

   workbook.write(fileout);
  }

 }
}

如您所见,代码中没有任何内容已本地化。全部为en_US。公式中的函数名称为ROUND,函数参数之间的分隔符为逗号,与列表分隔符相同,双精度值十进制分隔符为点。数字格式代码也是en_US

Excel.xlsx文件中存储的内容均未进行任何本地化。

但是如果我用德语Excel.xlsx打开Excel,则看起来像这样:

enter image description here

请注意公式=RUNDEN(A3;2)。函数名称翻译为德语,函数参数之间的分隔符为分号,相同的名称为列表分隔符,双精度值的十进制分隔符为逗号,千位分隔符为点。

数字格式代码现在也是德语:

enter image description here

这是为什么?主要是因为它是德语Excel应用程序。而且还因为Windows区域设置决定了日期格式

enter image description here

...以及十进制分隔符,列表分隔符和千位分隔符。

enter image description here