如何使用POIparsingExcel文件中的UTF-8字符

我一直在使用POI来成功parsingXLS和XLSX文件。 但是,我无法从Excel电子表格中正确提取特殊字符,如中文或日文等UTF-8编码字符。 我已经想出了如何从UTF-8编码的csv或制表符分隔的文件中提取数据,但没有运气的Excel文件。 谁能帮忙?

编辑: 评论中的代码片段

HSSFSheet sheet = workbook.getSheet(worksheet); HSSFEvaluationWorkbook ewb = HSSFEvaluationWorkbook.create(workbook); while (rowCtr <= lastRow && !rowBreakOut) { Row row = sheet.getRow(rowCtr);//rows.next(); for (int col=firstCell; col<lastCell && !breakOut; col++) { Cell cell; cell = row.getCell(col,Row.RETURN_BLANK_AS_NULL); if (ctype == Cell.CELL_TYPE_STRING) { sValue = cell.getStringCellValue(); log.warn("String value = "+sValue); String encoded = URLEncoder.encode(sValue, "UTF-8"); log.warn("URL-encoded with UTF-8: " + encoded); .... 

从Excel文件中提取波斯语文本时,我遇到了同样的问题。 我正在使用Eclipse,只需要“项目” – >“属性”,并将“文本文件编码”更改为UTF-8即可解决问题。

在POI你可以这样使用:

 Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet("new sheet"); // Create a row and put some cells in it. Rows are 0 based. Row row = sheet.createRow(1); // Create a new font and alter it. Font font = wb.createFont(); font.setCharSet(FontCharset.ARABIC.getValue()); font.setFontHeightInPoints((short)24); font.setFontName("B Nazanin"); font.setItalic(true); font.setStrikeout(true); // Fonts are set into a style so create a new one to use. CellStyle style = wb.createCellStyle(); style.setFont(font); // Create a cell and put a value in it. Cell cell = row.createCell(1); cell.setCellValue("سلام"); cell.setCellStyle(style); // Write the output to a file FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close(); 

并可以在FontCharset中使用另一个字符集

解决方法很简单,可以读取任何编码(非英文字符)的单元格string值; 只需使用以下方法:

 sValue = cell.getRichStringCellValue().getString(); 

代替:

 sValue = cell.getStringCellValue(); 

这适用于UTF-8编码的字符,如中文,阿拉伯文或日文。

PS如果有人使用命令行实用程序nullpunkt / excel-to-json(利用“Apache POI”库),通过replace“getStringCellValue()”的出现来修改文件转换器/ ExcelToJsonConverter.java,以避免读取非英文字符作为“???”。

使用UTF获取字节如下

 cell.getStringCellValue().getBytes(Charset.forName("UTF-8"));