2012-02-08 103 views
7

我一直在使用POI來成功解析XLS和XLSX文件。但是,我無法從Excel電子表格中正確提取特殊字符,如中文或日文等UTF-8編碼字符。我已經想出瞭如何從UTF-8編碼的csv或製表符分隔的文件中提取數據,但沒有運行Excel文件。誰能幫忙?如何使用POI解析Excel文件中的UTF-8字符

編輯:從意見代碼片段)

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); 
     .... 
+0

您可以指向您正在使用的POI API的各個部分,還是向我們展示一些代碼?這將有助於我們推薦可幫助調試的API更改和/或診斷。 – 2012-02-08 23:29:17

+0

Excel不會將字符存儲爲UTF-8,所以我認爲您可能在某處感到困惑... – Gagravarr 2012-02-09 09:55:55

+0

Excel文件的屏幕截圖: – user1198370 2012-02-09 16:41:16

回答

7

我在從一個Excel文件中提取文本波斯人有同樣的問題。我正在使用Eclipse,只需轉到Project - > Properties並將「文本文件編碼」更改爲UTF-8即可解決問題。

+0

工作就像一個魅力。謝謝。 – Abhishek 2012-09-25 13:17:21

3

在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(); 

,並可以使用UTF如下

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

獲取字節,讀任何編碼的單元格字符串值(非英文字符);只需使用下面的方法:

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

代替:

sValue = cell.getStringCellValue(); 

這適用於像中國,阿拉伯語或日語UTF-8編碼的字符。

PS如果有人正在使用命令行實用程序nullpunkt/Excel到JSON,其利用「阿帕奇POI」文庫,通過用「getStringCellValue()」的發生來修改文件轉換器/ ExcelToJsonConverter.java避免將非英文字符讀作「???」。

1

解決方法很簡單使用其他字符集的字體字符集