Apache POI是Apache软件基金会的开源项目,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。 .NET的开发人员则可以利用NPOI (POI for .NET) 来存取 Microsoft Office文档的功能。
需要的mavan依赖:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16<!-- Excel poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.9</version> </dependency>
ExcelUtil.java
复制代码
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272package com.citywy.controller; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import org.apache.poi.hssf.usermodel.HSSFCell; 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.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.CellRangeAddress; public class ExcelUtil { public static void main(String[] args){ ExcelUtil excelUtil = new ExcelUtil(); //读取excel数据 ArrayList<Map<String,String>> result = excelUtil.readExcelToObj("d:\first\a.xlsx"); for(Map<String,String> map:result){ System.out.println("输出:"+map); } } /** * 读取excel数据 * @param path */ private ArrayList<Map<String,String>> readExcelToObj(String path) { Workbook wb = null; ArrayList<Map<String,String>> result = null; try { wb = WorkbookFactory.create(new File(path)); result = readExcel(wb, 0, 1, 0); } catch (InvalidFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } /** * 读取excel文件 * @param wb * @param sheetIndex sheet页下标:从0开始 * @param startReadLine 开始读取的行:从0开始 * @param tailLine 去除最后读取的行 */ private ArrayList<Map<String,String>> readExcel(Workbook wb,int sheetIndex, int startReadLine, int tailLine) { Sheet sheet = wb.getSheetAt(sheetIndex); Row row = null; ArrayList<Map<String,String>> result = new ArrayList<Map<String,String>>(); for(int i=startReadLine; i<sheet.getLastRowNum()-tailLine+1; i++) { row = sheet.getRow(i); Map<String,String> map = new HashMap<String,String>(); for(Cell c : row) { String returnStr = ""; boolean isMerge = isMergedRegion(sheet, i, c.getColumnIndex()); //判断是否具有合并单元格 if(isMerge) { String rs = getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex()); // System.out.print(rs + "------ "); returnStr = rs; }else { // System.out.print(c.getRichStringCellValue()+"++++ "); returnStr = c.getRichStringCellValue().getString(); } if(c.getColumnIndex()==0){ map.put("id",returnStr); }else if(c.getColumnIndex()==1){ map.put("base",returnStr); }else if(c.getColumnIndex()==2){ map.put("siteName",returnStr); }else if(c.getColumnIndex()==3){ map.put("articleName",returnStr); }else if(c.getColumnIndex()==4){ map.put("mediaName",returnStr); }else if(c.getColumnIndex()==5){ map.put("mediaUrl",returnStr); }else if(c.getColumnIndex()==6){ map.put("newsSource",returnStr); }else if(c.getColumnIndex()==7){ map.put("isRecord",returnStr); }else if(c.getColumnIndex()==8){ map.put("recordTime",returnStr); }else if(c.getColumnIndex()==9){ map.put("remark",returnStr); } } result.add(map); } return result; } /** * 获取合并单元格的值 * @param sheet * @param row * @param column * @return */ public String getMergedRegionValue(Sheet sheet ,int row , int column){ int sheetMergeCount = sheet.getNumMergedRegions(); for(int i = 0 ; i < sheetMergeCount ; i++){ CellRangeAddress ca = sheet.getMergedRegion(i); int firstColumn = ca.getFirstColumn(); int lastColumn = ca.getLastColumn(); int firstRow = ca.getFirstRow(); int lastRow = ca.getLastRow(); if(row >= firstRow && row <= lastRow){ if(column >= firstColumn && column <= lastColumn){ Row fRow = sheet.getRow(firstRow); Cell fCell = fRow.getCell(firstColumn); return getCellValue(fCell) ; } } } return null ; } /** * 判断合并了行 * @param sheet * @param row * @param column * @return */ private boolean isMergedRow(Sheet sheet,int row ,int column) { int sheetMergeCount = sheet.getNumMergedRegions(); for (int i = 0; i < sheetMergeCount; i++) { CellRangeAddress range = sheet.getMergedRegion(i); int firstColumn = range.getFirstColumn(); int lastColumn = range.getLastColumn(); int firstRow = range.getFirstRow(); int lastRow = range.getLastRow(); if(row == firstRow && row == lastRow){ if(column >= firstColumn && column <= lastColumn){ return true; } } } return false; } /** * 判断指定的单元格是否是合并单元格 * @param sheet * @param row 行下标 * @param column 列下标 * @return */ private boolean isMergedRegion(Sheet sheet,int row ,int column) { int sheetMergeCount = sheet.getNumMergedRegions(); for (int i = 0; i < sheetMergeCount; i++) { CellRangeAddress range = sheet.getMergedRegion(i); int firstColumn = range.getFirstColumn(); int lastColumn = range.getLastColumn(); int firstRow = range.getFirstRow(); int lastRow = range.getLastRow(); if(row >= firstRow && row <= lastRow){ if(column >= firstColumn && column <= lastColumn){ return true; } } } return false; } /** * 判断sheet页中是否含有合并单元格 * @param sheet * @return */ private boolean hasMerged(Sheet sheet) { return sheet.getNumMergedRegions() > 0 ? true : false; } /** * 合并单元格 * @param sheet * @param firstRow 开始行 * @param lastRow 结束行 * @param firstCol 开始列 * @param lastCol 结束列 */ private void mergeRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) { sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol)); } /** * 获取单元格的值 * @param cell * @return */ public String getCellValue(Cell cell){ if(cell == null) return ""; if(cell.getCellType() == Cell.CELL_TYPE_STRING){ return cell.getStringCellValue(); }else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){ return String.valueOf(cell.getBooleanCellValue()); }else if(cell.getCellType() == Cell.CELL_TYPE_FORMULA){ return cell.getCellFormula() ; }else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){ return String.valueOf(cell.getNumericCellValue()); } return ""; } /** * 从excel读取内容 */ public static void readContent(String fileName) { boolean isE2007 = false; //判断是否是excel2007格式 if(fileName.endsWith("xlsx")) isE2007 = true; try { InputStream input = new FileInputStream(fileName); //建立输入流 Workbook wb = null; //根据文件格式(2003或者2007)来初始化 if(isE2007) wb = new XSSFWorkbook(input); else wb = new HSSFWorkbook(input); Sheet sheet = wb.getSheetAt(0); //获得第一个表单 Iterator<Row> rows = sheet.rowIterator(); //获得第一个表单的迭代器 while (rows.hasNext()) { Row row = rows.next(); //获得行数据 System.out.println("Row #" + row.getRowNum()); //获得行号从0开始 Iterator<Cell> cells = row.cellIterator(); //获得第一行的迭代器 while (cells.hasNext()) { Cell cell = cells.next(); System.out.println("Cell #" + cell.getColumnIndex()); switch (cell.getCellType()) { //根据cell中的类型来输出数据 case HSSFCell.CELL_TYPE_NUMERIC: System.out.println(cell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_STRING: System.out.println(cell.getStringCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: System.out.println(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: System.out.println(cell.getCellFormula()); break; default: System.out.println("unsuported sell type======="+cell.getCellType()); break; } } } } catch (IOException ex) { ex.printStackTrace(); } } }
附加个人需求:
复制代码
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/** * str最后一行读不到,手动最后加一行废数据 * 附加:将读取的内容合并为 * 【高危职业】什么是高危职业_十大高危职业_xxx_xxx_xxx 最多8条 * 所属栏目读取最后一个/后的值 职业病防治 */ public static void main(String[] args){ ExcelUtil excelUtil = new ExcelUtil(); //读取excel数据 ArrayList<Map<String,String>> result = excelUtil.readExcelToObj("d:\xreadexcel\a.xlsx"); Map<String, Object> result1 = new HashMap<String, Object>(); String str=""; for(Map<String,String> map:result){ String id = map.get("id"); String value = map.get("base"); String menu = map.get("siteName"); if(menu.contains("/")){ menu=menu.substring(menu.lastIndexOf("/")+1); } if(result1.containsKey(id)){ if(getCount(str, "_")<7){ str=str+"_"+value; } }else{ if(!str.equals("")){ System.out.println(str); //【高危职业】什么是高危职业_十大高危职业_..._..._...最多8条 } //System.out.println(id); //高危职业 //System.out.println(menu.trim());//职业病防治 str="【"+id+"】"+value; result1.put(id, value); } } } /** * 获取字符串指定字符个数 * @param str * @param tag * @return */ public static int getCount(String str, String tag) { int index = 0; int count = 0; while ((index = str.indexOf(tag)) != -1 ) { str = str.substring(index + tag.length()); count++; } return count; }
转载:https://www.cnblogs.com/jiuchongxiao/p/5659884.html
最后
以上就是坦率信封最近收集整理的关于工具方法:java读取Excel合并单元格(简单实例)的全部内容,更多相关工具方法内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复