-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExcelReader.java
609 lines (551 loc) · 16.2 KB
/
ExcelReader.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.poi.common.usermodel.Hyperlink;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
/*
* The Class ExcelReader
*
* @author mayuragarwal25
*/
public class ExcelReader {
public String path;
public FileInputStream fis = null;
public FileOutputStream fileOut =null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row =null;
private XSSFCell cell = null;
private HashMap<String,HashMap<String, Integer>> sheetMap=null;
private HashMap<String, Integer> mapping=null;
public ExcelReader(String path) {
this.path=path;
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
sheetMap=new HashMap<String,HashMap<String,Integer>>();
} catch (Exception e) {
e.printStackTrace();
}
}
/* Function to get number of rows for given sheet name in current workbook.
* It returns 0 if sheet does'nt exists
* @param name of sheet
* @return the row count in the sheet
*/
public int getRowCount(String sheetName){
sheet = workbook.getSheet(sheetName);
if(sheet!=null){
int number=sheet.getLastRowNum()+1;
return number;
}
return 0;
}
/*Function to get cell data in a given cell for a given sheet.
* The column no are mapped against uppermost row of the sheet
* It returns empty string if cell does'nt exist or is empty
* @param Sheetname for given workbook
* @param Column name for cell (starts with 0)
* @param Row no for cell (starts with 0)
* @return the data from a cell in String format (empty String if cell or sheet or cell data does'nt exist)
*/
public String getCellData(String sheetName,String colName,int rowNum){
if(rowNum <=0){
return "";
}
int index = workbook.getSheetIndex(sheetName);
int colNumber=-1;
if(index==-1){
return "";
}
sheet = workbook.getSheetAt(index);
if(!sheetMap.containsKey(sheetName)||(sheetMap.get(sheetName)==null)){
mapSheet(sheet,sheetName);
}
mapping=sheetMap.get(sheetName);
if(!mapping.containsKey(colName)||(mapping.get(colName)==null)){
return "";
}
colNumber=mapping.get(colName);
return this.getCellData(sheetName, colNumber, rowNum);
}
/*Function to get cell data in a given cell for a given sheet.
* It returns empty string if cell does'nt exist or is empty
* @param Sheetname for given workbook
* @param Column no for cell (starts with 0)
* @param Row no for cell (starts with 0)
* @return the data from a cell in String format (empty String if cell or sheet or cell data does'nt exist)
*/
public String getCellData(String sheetName,int colNum,int rowNum){
try{
if(rowNum <0){
return "";
}
int index = workbook.getSheetIndex(sheetName);
if(index==-1){
return "";
}
sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum);
if(row==null){
return "";
}
cell = row.getCell(colNum);
if(cell==null){
return "";
}
if(cell.getCellType()==CellType.STRING){
return cell.getStringCellValue().trim();
}
else if(cell.getCellType()==CellType.NUMERIC || cell.getCellType()==CellType.NUMERIC ){
String cellText = String.valueOf(cell.getNumericCellValue());
if (DateUtil.isCellDateFormatted(cell)) {
// format in form of MM/DD/YY
double d = cell.getNumericCellValue();
Calendar cal =Calendar.getInstance();
cal.setTime(DateUtil.getJavaDate(d));
cellText =
(String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.MONTH)+1 + "/" +
cal.get(Calendar.DAY_OF_MONTH) + "/" +
cellText;
}
return cellText.trim();
}else if(cell.getCellType()==CellType.BLANK){
return "";
}
else {
return String.valueOf(cell.getBooleanCellValue()).trim();
}
}
catch(Exception e){
e.printStackTrace();
return "";
}
}
/*Function to set cell data in a given cell for a given sheet.
* The column no are mapped against uppermost row of the sheet
* It returns false if writing failed or colNum does'nt exist.
* The changes made is thread safe
* @param Sheetname for given workbook
* @param Column name for cell (starts with 0)
* @param Row no for cell (starts with 0)
* @param Data to be wrote to cell
* @return true if data is set successfully else false
*/
public boolean setCellData(String sheetName,String colName,int rowNum, String data){
try{
if(rowNum<=0){
return false;
}
int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1){
return false;
}
sheet = workbook.getSheetAt(index);
if(!sheetMap.containsKey(sheetName)||(sheetMap.get(sheetName)==null)){
mapSheet(sheet,sheetName);
}
mapping=sheetMap.get(sheetName);
if(!mapping.containsKey(colName)||(mapping.get(colName)==null)){
return false;
}
colNum=mapping.get(colName);
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum);
if (row == null){
row = sheet.createRow(rowNum);
}
cell = row.getCell(colNum);
if (cell == null){
cell = row.createCell(colNum);
}
cell.setCellValue(data);
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
/*Function to set cell data and URL in a given cell for a given sheet.
* The column no are mapped against uppermost row of the sheet
* It returns false if writing failed or colNum does'nt exist
* It is thread safe no changes made are presisted to file
* @param Sheetname for given workbook
* @param Column name for cell (starts with 0)
* @param Row no for cell (starts with 0)
* @param Data to be wrote to cell
* @param URL to be added to
* @return true if data is set successfully else false
*/
public boolean setCellData(String sheetName,String colName,int rowNum, String data,String url){
try{
if(rowNum<=0){
return false;
}
int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1){
return false;
}
sheet = workbook.getSheetAt(index);
if(!sheetMap.containsKey(sheetName)||(sheetMap.get(sheetName)==null)){
mapSheet(sheet,sheetName);
}
mapping=sheetMap.get(sheetName);
if(!mapping.containsKey(colName)||(mapping.get(colName)==null)){
return false;
}
colNum=mapping.get(colName);
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum);
if (row == null){
row = sheet.createRow(rowNum);
}
cell = row.getCell(colNum);
if (cell == null){
cell = row.createCell(colNum);
}
cell.setCellValue(data);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
//cell style for hyperlinks
CellStyle hlinkstyle = workbook.createCellStyle();
XSSFFont hlinkfont = workbook.createFont();
hlinkfont.setUnderline(Font.U_SINGLE);
hlinkfont.setColor(IndexedColors.BLUE.getIndex());
hlinkstyle.setFont(hlinkfont);
XSSFHyperlink link = createHelper.createHyperlink(HyperlinkType.FILE);
link.setAddress(url);
cell.setHyperlink(link);
cell.setCellStyle(hlinkstyle);
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
/*Function to add sheet to current workbook with given sheetname
* Thread safe
* @param Sheet name
* @return true if sheet is created successfully else false
*/
public boolean addSheet(String sheetname){
try {
workbook.createSheet(sheetname);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/*
* Function to remove sheet of given name from current workbook
* thread safe
* @param sheet name
* @return true if sheet is removed successfully else false if sheet does not exist or not removed
*/
public boolean removeSheet(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1){
return false;
}
try {
workbook.removeSheetAt(index);
sheetMap.remove(sheetName);
} catch (Exception e) {
e.printStackTrace();
return false;
}
mapping.remove(sheetName);
return true;
}
/* Function adds column to given sheet with given name
* Thread safe
* @param Sheet name
* @param Column name
* @return true if column is created successfully false otherwise
*/
public boolean addColumn(String sheetName,String colName){
try{
int index = workbook.getSheetIndex(sheetName);
if(index==-1){
return false;
}
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColorPredefined.GREY_40_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
sheet=workbook.getSheetAt(index);
row = sheet.getRow(0);
if (row == null){
row = sheet.createRow(0);
}
if(row.getLastCellNum() == -1){
cell = row.createCell(0);
}
else{
int colNum=row.getLastCellNum();
cell = row.createCell(row.getLastCellNum());
cell.setCellValue(colName);
cell.setCellStyle(style);
sheetMap.get(sheetName).put(colName, colNum);
}
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
/* Function removes column to given sheet with given column no
* Thread safe
* @param Sheet name
* @param Column no
* @return true if column is removed successfully false otherwise
*/
public boolean removeColumn(String sheetName, int colNum) {
try{
if(!isSheetExist(sheetName)){
return false;
}
sheet=workbook.getSheet(sheetName);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_40_PERCENT.getIndex());
style.setFillPattern(FillPatternType.NO_FILL);
for(int i =0;i<getRowCount(sheetName);i++){
row=sheet.getRow(i);
if(row!=null){
cell=row.getCell(colNum);
if(cell!=null){
cell.setCellStyle(style);
row.removeCell(cell);
}
}
}
removeColumnMapping(sheetName, colNum);
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
/* Function removes column to given sheet with given column name
* Thread safe
* @param Sheet name
* @param Column name
* @return true if column is removed successfully false otherwise
*/
public boolean removeColumn(String sheetName, String colName) {
try{
if(!isSheetExist(sheetName)){
return false;
}
sheet=workbook.getSheet(sheetName);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColorPredefined.GREY_40_PERCENT.getIndex());
style.setFillPattern(FillPatternType.NO_FILL);
int colNum;
if(!sheetMap.containsKey(sheetName)||(sheetMap.get(sheetName)==null)){
mapSheet(sheet,sheetName);
}
mapping=sheetMap.get(sheetName);
if(!mapping.containsKey(colName)||(mapping.get(colName)==null)){
return false;
}
colNum=mapping.get(colName);
for(int i =0;i<getRowCount(sheetName);i++){
row=sheet.getRow(i);
if(row!=null){
cell=row.getCell(colNum);
if(cell!=null){
cell.setCellStyle(style);
row.removeCell(cell);
}
}
}
sheetMap.get(sheetName).remove(colName);
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
/* Function to find that a sheet exists with given name in current workbook
* @param Sheet name
* @return true if sheet exists false otherwise
*/
public boolean isSheetExist(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1){
index=workbook.getSheetIndex(sheetName.toUpperCase());
if(index==-1) {
return false;
}
else {
return true;
}
}
else {
return true;
}
}
/* Function to count no column in given sheet
* @param Sheet name
* @return no of column or -1 sheet is empty or does'nt exists
*/
public int getColumnCount(String sheetName){
// check if sheet exists
if(!isSheetExist(sheetName)){
return -1;
}
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
if(row==null){
return -1;
}
return row.getLastCellNum();
}
/* Function to attach URL and to given cell
* @param Sheet name
* @param Column name
* @param index as row no
* @param URL
* @return true if column is removed successfully false otherwise
*/
@Deprecated
public boolean addHyperLink(String sheetName,String screenShotColName,String testCaseName,int index,String url,String message){
url=url.replace('\\', '/');
if(!isSheetExist(sheetName)){
return false;
}
sheet = workbook.getSheet(sheetName);
for(int i=1;i<getRowCount(sheetName);i++){
if(getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)){
setCellData(sheetName, screenShotColName, i+index, message,url);
break;
}
}
return true;
}
/* Function gives first row no containing a given value in given column
* @param Sheet name
* @param Column name
* @param Cell value
* @return First encountered row no with given value or -1 otherwise
*/
public int getCellRowNum(String sheetName,String colName,String cellValue){
for(int i=1;i<getRowCount(sheetName);i++){
if(getCellData(sheetName,colName , i).equalsIgnoreCase(cellValue)){
return i;
}
}
return -1;
}
/* Function gives first row no containing a given value in given column
* @param Sheet name
* @param Column name
* @param Cell value
* @return All encountered row no with given value or -1 otherwise
*/
public ArrayList<Integer> getCellRowNumList(String sheetName,String colName,String cellValue){
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=1;i<getRowCount(sheetName);i++){
if(getCellData(sheetName,colName , i).equalsIgnoreCase(cellValue)){
list.add(i);
}
}
return list;
}
/*
* Adjusts all columns width to fit the contents in given sheet.
* This process can be relatively slow on large sheets, so this should normally only be called once per column, at the end of your processing.
* @param sheetName
*/
public void beautify(String sheetName){
if(!isSheetExist(sheetName)){
System.out.println("Sheet does'nt exists");
}
else{
sheet=workbook.getSheet(sheetName);
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
sheet.autoSizeColumn(i);
}
}
}
public void beautify(Sheet sheet){
Row row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
sheet.autoSizeColumn(i);
}
}
public boolean dumpWorkbookToFile(){
try {
fileOut=new FileOutputStream(this.path);
Iterator<Sheet> sheets=workbook.sheetIterator();
while(sheets.hasNext()){
this.beautify(sheets.next());
}
} catch (FileNotFoundException e) {
// DriverApp.APPLICATION_LOGS.info("No file found of given path :"+this.path +e.getMessage());
System.out.println("No file found of given path :"+this.path +e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
/*
* An internel function to add map column no against Column headers,
* i.e name written in row[0] of that column.
* It also map these maps to sheetNames
* @param sheet
* @param sheetName
*/
protected void mapSheet(XSSFSheet sheet,String sheetName){
XSSFRow mappingRow = sheet.getRow(0);
mapping=new HashMap<String,Integer>();
if(mappingRow==null){
sheetMap.put(sheetName, mapping);
return ;
}
for(int i=0;i<mappingRow.getLastCellNum();i++){
mapping.put(mappingRow.getCell(i).getStringCellValue().trim(),i);
}
sheetMap.put(sheetName, mapping);
return ;
}
/*
* An internel function to remove key, value pair of column no against Column headers from sheet map.
* @param sheetName
* @param colNum
*/
private void removeColumnMapping(String sheetName, int colNum) {
Map<String,Integer> mp = sheetMap.get(sheetName);
for(Entry<String, Integer> et:mp.entrySet()){
if(et.getValue()==colNum){
mp.remove(et.getKey());
}
}
}
}