Java 讀取Excel格式xls、xlsx數據工具類
需要POI的jar包支持
調用方式
1
2
|
ReadExcelTest excelTest = new ReadExcelTest(); excelTest.readExcel( "D:\\data1.xlsx" ); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
|
package com.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.xmlbeans.impl.piccolo.io.FileFormatException; public class ReadExcelTest { private static final String EXTENSION_XLS = "xls" ; private static final String EXTENSION_XLSX = "xlsx" ; /*** * <pre> * 取得Workbook對象(xls和xlsx對象不同,不過都是Workbook的實現類) * xls:HSSFWorkbook * xlsx:XSSFWorkbook * @param filePath * @return * @throws IOException * </pre> */ private Workbook getWorkbook(String filePath) throws IOException { Workbook workbook = null ; InputStream is = new FileInputStream(filePath); if (filePath.endsWith(EXTENSION_XLS)) { workbook = new HSSFWorkbook(is); } else if (filePath.endsWith(EXTENSION_XLSX)) { workbook = new XSSFWorkbook(is); } return workbook; } /** * 文件檢查 * @param filePath * @throws FileNotFoundException * @throws FileFormatException */ private void preReadCheck(String filePath) throws FileNotFoundException, FileFormatException { // 常規檢查 File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException( "傳入的文件不存在:" + filePath); } if (!(filePath.endsWith(EXTENSION_XLS) || filePath.endsWith(EXTENSION_XLSX))) { throw new FileFormatException( "傳入的文件不是excel" ); } } /** * 讀取excel文件內容 * @param filePath * @throws FileNotFoundException * @throws FileFormatException */ public void readExcel(String filePath) throws FileNotFoundException, FileFormatException { // 檢查 this .preReadCheck(filePath); // 獲取workbook對象 Workbook workbook = null ; try { workbook = this .getWorkbook(filePath); // 讀文件 一個sheet一個sheet地讀取 for ( int numSheet = 0 ; numSheet < workbook.getNumberOfSheets(); numSheet++) { Sheet sheet = workbook.getSheetAt(numSheet); if (sheet == null ) { continue ; } System.out.println( "=======================" + sheet.getSheetName() + "=========================" ); int firstRowIndex = sheet.getFirstRowNum(); int lastRowIndex = sheet.getLastRowNum(); // 讀取首行 即,表頭 Row firstRow = sheet.getRow(firstRowIndex); for ( int i = firstRow.getFirstCellNum(); i <= firstRow.getLastCellNum(); i++) { Cell cell = firstRow.getCell(i); String cellValue = this .getCellValue(cell, true ); System.out.print( " " + cellValue + "\t" ); } System.out.println( "" ); // 讀取數據行 for ( int rowIndex = firstRowIndex + 1 ; rowIndex <= lastRowIndex; rowIndex++) { Row currentRow = sheet.getRow(rowIndex); // 當前行 int firstColumnIndex = currentRow.getFirstCellNum(); // 首列 int lastColumnIndex = currentRow.getLastCellNum(); // 最后一列 for ( int columnIndex = firstColumnIndex; columnIndex <= lastColumnIndex; columnIndex++) { Cell currentCell = currentRow.getCell(columnIndex); // 當前單元格 String currentCellValue = this .getCellValue(currentCell, true ); // 當前單元格的值 System.out.print(currentCellValue + "\t" ); } System.out.println( "" ); } System.out.println( "======================================================" ); } } catch (Exception e) { e.printStackTrace(); } finally { if (workbook != null ) { try { workbook.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 取單元格的值 * @param cell 單元格對象 * @param treatAsStr 為true時,當做文本來取值 (取到的是文本,不會把“1”取成“1.0”) * @return */ private String getCellValue(Cell cell, boolean treatAsStr) { if (cell == null ) { return "" ; } if (treatAsStr) { // 雖然excel中設置的都是文本,但是數字文本還被讀錯,如“1”取成“1.0” // 加上下面這句,臨時把它當做文本來讀取 cell.setCellType(Cell.CELL_TYPE_STRING); } if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { return String.valueOf(cell.getBooleanCellValue()); } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { return String.valueOf(cell.getNumericCellValue()); } else { return String.valueOf(cell.getStringCellValue()); } } } |
使用poi讀取xlsx格式的Excel總結
今天遇到的坑
公司實習生項目,其中有個功能是讀取Excel數據,之前做過以為很快就能搞定,萬萬沒想到,本地寫的一切都正常,可就在要發布生產了,尼瑪測試環境居然出bug了讀取xlsx格式的Excel,讀不了,本地完全可以,就是測試環境上不行,心里一萬只曹尼瑪奔過
下面是代碼部分:
我使用的是springmvc,首先是controller部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
@RequestMapping ( "ReadFromExcel" ) @ResponseBody public Response ReadFromExcel( @RequestParam (value = "file" ) MultipartFile file, @RequestAttribute ( "userNo" ) String userNo) { try { //校驗文件 checkFile(file); List<ArrayList<String>> list =excelService.readExcel(file); if (CollectionUtils.isEmpty(list)) { return new Response(ERROR_CODE, "導入的文件沒有數據" , false ); } } catch (Exception e){ logger.error( "ReadFromExcel異常" ,e); } return new Response(ERROR_CODE, "導入失敗" , false ); } private void checkFile(MultipartFile file) throws IOException { //判斷文件是否存在 if ( null == file){ logger.error( "文件不存在!" ); throw new FileNotFoundException( "文件不存在!" ); } //獲得文件名 String fileName = file.getOriginalFilename(); logger.info( "ReadFromExcel fileName" ,fileName); //判斷文件是否是excel文件 if (!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){ logger.error(fileName + "不是excel文件" ); throw new IOException(fileName + "不是excel文件" ); } } |
然后是讀取Excel文件部分,也就是service部分
這些網上隨便一搜都能搜到
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
@Override public List<ArrayList<String>> readExcel(MultipartFile file) { List<ArrayList<String>> list = new ArrayList<ArrayList<String>>(); try { // 檢查文件 logger.info( "ExcelServiceImpl 獲取文件名" , file.getOriginalFilename()); // 獲得Workbook工作薄對象 Workbook workbook = getWorkBook(file); // 創建返回對象,把每行中的值作為一個數組,所有行作為一個集合返回 logger.info( "獲得Workbook工作薄對象" , file.getOriginalFilename()); if (workbook != null ) { for ( int sheetNum = 0 ; sheetNum < workbook.getNumberOfSheets(); sheetNum++) { // 獲得當前sheet工作表 Sheet sheet = workbook.getSheetAt(sheetNum); logger.info( "獲得當前sheet工作表" , file.getOriginalFilename()); if (sheet == null ) { continue ; } // 獲得當前sheet的開始行 int firstRowNum = sheet.getFirstRowNum(); // 獲得當前sheet的結束行 int lastRowNum = sheet.getLastRowNum(); // 循環除了第一行的所有行 for ( int rowNum = firstRowNum + 1 ; rowNum <= lastRowNum; rowNum++) { // 獲得當前行 Row row = sheet.getRow(rowNum); if (row == null ) { continue ; } // 獲得當前行的開始列 int firstCellNum = row.getFirstCellNum(); // 獲得當前行的列數 int lastCellNum = row.getPhysicalNumberOfCells(); ArrayList<String> cells = new ArrayList<>(); // 循環當前行 for ( int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) { Cell cell = row.getCell(cellNum); cells.add(getCellValue(cell)); } list.add(cells); } } } } catch (Exception e) { logger.error( "readExcel Exception" , e.getMessage()); } return list; } private Workbook getWorkBook(MultipartFile file) { // 獲得文件名 String fileName = file.getOriginalFilename(); // 創建Workbook工作薄對象,表示整個excel Workbook workbook = null ; try { // 獲取excel文件的io流 InputStream is = file.getInputStream(); logger.info( "獲取excel文件的io流" ); // 根據文件后綴名不同(xls和xlsx)獲得不同的Workbook實現類對象 if (fileName.endsWith(xls)) { // 2003 workbook = new HSSFWorkbook(is); } else if (fileName.endsWith(xlsx)) { // 2007 workbook = new XSSFWorkbook(is); } } catch (Exception e) { logger.info(e.getMessage()); } return workbook; } private String getCellValue(Cell cell) { String cellValue = "" ; if (cell == null ) { return cellValue; } // 把數字當成String來讀,避免出現1讀成1.0的情況 if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { cell.setCellType(Cell.CELL_TYPE_STRING); } // 判斷數據的類型 switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: // 數字 cellValue = String.valueOf(cell.getNumericCellValue()); break ; case Cell.CELL_TYPE_STRING: // 字符串 cellValue = String.valueOf(cell.getStringCellValue()); break ; case Cell.CELL_TYPE_BOOLEAN: // Boolean cellValue = String.valueOf(cell.getBooleanCellValue()); break ; case Cell.CELL_TYPE_FORMULA: // 公式 cellValue = String.valueOf(cell.getCellFormula()); break ; case Cell.CELL_TYPE_BLANK: // 空值 cellValue = "" ; break ; case Cell.CELL_TYPE_ERROR: // 故障 cellValue = "非法字符" ; break ; default : cellValue = "未知類型" ; break ; } return cellValue; } |
spring-servlet.xml 配置如下
1
2
3
4
5
|
< bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" > < property name = "defaultEncoding" value = "utf-8" /> < property name = "maxUploadSize" value = "10485760000" /> < property name = "maxInMemorySize" value = "40960" /> </ bean > |
最初的maven是這么配置的
1
2
3
4
5
6
7
8
9
10
|
< dependency > < groupId >org.apache.poi</ groupId > < artifactId >poi-ooxml</ artifactId > < version >3.9</ version > </ dependency > < dependency > < groupId >org.apache.poi</ groupId > < artifactId >poi</ artifactId > < version >3.9</ version > </ dependency > |
好了,本地走起來完全沒毛病,很開心,終于可以發布了,可以早點回學校寫論文了,發到測試環境,測試讀取xls也是沒毛病,可尼瑪,想讀取個xlsx的文件試試看,網頁提示404,這什么鬼,打日志查問題,還一直以為是前端的哥們出問題,可一看日志不對啊,請求已經進來了,可是走到這一步就沒了 workbook = new XSSFWorkbook(is);這是為什么,趕緊網上查,一堆解決方案,一個個試,最后實在沒辦法把別人所有的方法一個個試,最后又加了如下jar包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
< dependency > < groupId >xmlbeans</ groupId > < artifactId >xmlbeans</ artifactId > < version >2.3.0</ version > < type >pom</ type > </ dependency > < dependency > < groupId >org.apache.poi</ groupId > < artifactId >poi-ooxml-schemas</ artifactId > < version >3.9</ version > </ dependency > < dependency > < groupId >org.apache.poi</ groupId > < artifactId >poi-scratchpad</ artifactId > < version >3.9</ version > </ dependency > < dependency > < groupId >org.apache.poi</ groupId > < artifactId >poi-examples</ artifactId > < version >3.9</ version > </ dependency > |
問題是解決了,可卻不知其所以然,記錄一下。以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/wangjianyu0115/article/details/51344853