1+ package com .anhtester .helpers ;
2+
3+ import org .apache .poi .ss .usermodel .*;
4+ import org .apache .poi .xssf .usermodel .XSSFCellStyle ;
5+ import org .apache .poi .xssf .usermodel .XSSFWorkbook ;
6+
7+ import java .io .*;
8+ import java .util .HashMap ;
9+ import java .util .Hashtable ;
10+ import java .util .Map ;
11+
12+ public class ExcelHelpers {
13+
14+ private FileInputStream fis ;
15+ private FileOutputStream fileOut ;
16+ private Workbook workbook ;
17+ private Sheet sheet ;
18+ private Cell cell ;
19+ private Row row ;
20+ private String excelFilePath ;
21+ private Map <String , Integer > columns = new HashMap <>();
22+
23+ public ExcelHelpers () {
24+ }
25+
26+ //Set Excel File
27+ public void setExcelFile (String excelPath , String sheetName ) {
28+ System .out .println ("Set Excel File: " + excelPath );
29+ System .out .println ("Sheet Name: " + sheetName );
30+
31+ try {
32+ File f = new File (excelPath );
33+
34+ if (!f .exists ()) {
35+ try {
36+ System .out .println ("File Excel path not found." );
37+ throw new FileNotFoundException ("File Excel path not found." );
38+ } catch (Exception e ) {
39+ e .printStackTrace ();
40+ }
41+ }
42+ if (sheetName .isEmpty ()) {
43+ try {
44+ System .out .println ("The Sheet Name is empty." );
45+ throw new FileNotFoundException ("The Sheet Name is empty." );
46+ } catch (Exception e ) {
47+ e .printStackTrace ();
48+ }
49+ }
50+
51+ fis = new FileInputStream (excelPath );
52+ workbook = WorkbookFactory .create (fis );
53+ sheet = workbook .getSheet (sheetName );
54+ //sh = wb.getSheetAt(0); //0 - index of 1st sheet
55+ if (sheet == null ) {
56+ //sh = wb.createSheet(sheetName);
57+ try {
58+ System .out .println ("Sheet name not found." );
59+ throw new RuntimeException ("Sheet name not found." );
60+ } catch (Exception e ) {
61+ e .printStackTrace ();
62+ }
63+ }
64+
65+ excelFilePath = excelPath ;
66+
67+ //adding all the column header names to the map 'columns'
68+ sheet .getRow (0 ).forEach (cell -> {
69+ columns .put (cell .getStringCellValue (), cell .getColumnIndex ());
70+ });
71+
72+ } catch (Exception e ) {
73+ e .getMessage ();
74+ System .out .println (e .getMessage ());
75+ }
76+ }
77+
78+ //This method takes the row number as a parameter and returns the data for that row.
79+ public Row getRowData (int rowNum ) {
80+ row = sheet .getRow (rowNum );
81+ return row ;
82+ }
83+
84+
85+ public Object [][] getExcelData (String excelPath , String sheetName ) {
86+ Object [][] data = null ;
87+ Workbook workbook = null ;
88+
89+ System .out .println ("Set Excel file " + excelPath );
90+ System .out .println ("Selected Sheet: " + sheetName );
91+
92+ try {
93+
94+ File f = new File (excelPath );
95+
96+ if (!f .exists ()) {
97+ try {
98+ System .out .println ("File Excel path not found." );
99+ throw new FileNotFoundException ("File Excel path not found." );
100+ } catch (Exception e ) {
101+ e .printStackTrace ();
102+ }
103+ }
104+ if (sheetName .isEmpty ()) {
105+ try {
106+ System .out .println ("The Sheet Name is empty." );
107+ throw new FileNotFoundException ("The Sheet Name is empty." );
108+ } catch (Exception e ) {
109+ e .printStackTrace ();
110+ }
111+ }
112+
113+ // load the file
114+ FileInputStream fis = new FileInputStream (excelPath );
115+
116+ // load the workbook
117+ workbook = new XSSFWorkbook (fis );
118+ // load the sheet
119+ Sheet sheet = workbook .getSheet (sheetName );
120+ // load the row
121+ Row row = sheet .getRow (0 );
122+
123+ int noOfRows = sheet .getPhysicalNumberOfRows ();
124+ int noOfCols = row .getLastCellNum ();
125+
126+ System .out .println (noOfRows + " - " + noOfCols );
127+
128+ Cell cell ;
129+ data = new Object [noOfRows - 1 ][noOfCols ];
130+
131+ //FOR loop runs from 1 to drop header line (headline is 0)
132+ for (int i = 1 ; i < noOfRows ; i ++) {
133+ for (int j = 0 ; j < noOfCols ; j ++) {
134+ row = sheet .getRow (i );
135+ cell = row .getCell (j );
136+
137+ //This is used to determine the data type from cells in Excel and then convert it to String for ease of reading
138+ switch (cell .getCellType ()) {
139+ case STRING :
140+ data [i - 1 ][j ] = cell .getStringCellValue ();
141+ break ;
142+ case NUMERIC :
143+ data [i - 1 ][j ] = String .valueOf (cell .getNumericCellValue ());
144+ break ;
145+ case BLANK :
146+ data [i - 1 ][j ] = "" ;
147+ break ;
148+ default :
149+ data [i - 1 ][j ] = null ;
150+ break ;
151+ }
152+ }
153+ }
154+ } catch (Exception e ) {
155+ e .getMessage ();
156+ throw new RuntimeException (e );
157+ }
158+ return data ;
159+ }
160+
161+ public Object [][] getDataHashTable (String excelPath , String sheetName , int startRow , int endRow ) {
162+ System .out .println ("Excel File: " + excelPath );
163+ System .out .println ("Sheet Name: " + sheetName );
164+
165+ Object [][] data = null ;
166+
167+ try {
168+
169+ File f = new File (excelPath );
170+
171+ if (!f .exists ()) {
172+ try {
173+ System .out .println ("File Excel path not found." );
174+ throw new RuntimeException ("File Excel path not found." );
175+ } catch (Exception e ) {
176+ e .printStackTrace ();
177+ }
178+ }
179+
180+ fis = new FileInputStream (excelPath );
181+ workbook = new XSSFWorkbook (fis );
182+ sheet = workbook .getSheet (sheetName );
183+
184+ int rows = getRows ();
185+ int columns = getColumns ();
186+
187+ System .out .println ("Row: " + rows + " - Column: " + columns );
188+ System .out .println ("StartRow: " + startRow + " - EndRow: " + endRow );
189+
190+ data = new Object [(endRow - startRow ) + 1 ][1 ];
191+ Hashtable <String , String > table = null ;
192+ for (int rowNums = startRow ; rowNums <= endRow ; rowNums ++) {
193+ table = new Hashtable <>();
194+ for (int colNum = 0 ; colNum < columns ; colNum ++) {
195+ table .put (getCellData (0 , colNum ), getCellData (rowNums , colNum ));
196+ }
197+ data [rowNums - startRow ][0 ] = table ;
198+ }
199+
200+ } catch (IOException e ) {
201+ e .printStackTrace ();
202+ System .out .println (e .getMessage ());
203+ }
204+
205+ return data ;
206+
207+ }
208+
209+ public int getRowContains (String sTestCaseName , int colNum ) {
210+ int i ;
211+ int rowCount = getRows ();
212+ for (i = 0 ; i < rowCount ; i ++) {
213+ if (getCellData (i , colNum ).equalsIgnoreCase (sTestCaseName )) {
214+ break ;
215+ }
216+ }
217+ return i ;
218+ }
219+
220+ public int getRows () {
221+ try {
222+ return sheet .getLastRowNum ();
223+ } catch (Exception e ) {
224+ System .out .println (e .getMessage ());
225+ throw (e );
226+ }
227+ }
228+
229+ public int getColumns () {
230+ try {
231+ row = sheet .getRow (0 );
232+ return row .getLastCellNum ();
233+ } catch (Exception e ) {
234+ System .out .println (e .getMessage ());
235+ throw (e );
236+ }
237+ }
238+
239+ // Get cell data
240+ public String getCellData (int rowNum , int colNum ) {
241+ try {
242+ cell = sheet .getRow (rowNum ).getCell (colNum );
243+ String CellData = null ;
244+ switch (cell .getCellType ()) {
245+ case STRING :
246+ CellData = cell .getStringCellValue ();
247+ break ;
248+ case NUMERIC :
249+ if (DateUtil .isCellDateFormatted (cell )) {
250+ CellData = String .valueOf (cell .getDateCellValue ());
251+ } else {
252+ CellData = String .valueOf ((long ) cell .getNumericCellValue ());
253+ }
254+ break ;
255+ case BOOLEAN :
256+ CellData = Boolean .toString (cell .getBooleanCellValue ());
257+ break ;
258+ case BLANK :
259+ CellData = "" ;
260+ break ;
261+ }
262+ return CellData ;
263+ } catch (Exception e ) {
264+ return "" ;
265+ }
266+ }
267+
268+ public String getCellData (int rowNum , String columnName ) {
269+ return getCellData (rowNum , columns .get (columnName ));
270+ }
271+
272+ public String getCellData (String columnName , int rowNum ) {
273+ return getCellData (rowNum , columns .get (columnName ));
274+ }
275+
276+ // Write data to excel sheet
277+ public void setCellData (String text , int rowNumber , int colNumber ) {
278+ try {
279+ row = sheet .getRow (rowNumber );
280+ if (row == null ) {
281+ row = sheet .createRow (rowNumber );
282+ }
283+ cell = row .getCell (colNumber );
284+
285+ if (cell == null ) {
286+ cell = row .createCell (colNumber );
287+ }
288+ cell .setCellValue (text );
289+
290+ XSSFCellStyle style = (XSSFCellStyle ) workbook .createCellStyle ();
291+ text = text .trim ().toLowerCase ();
292+ if (text == "pass" || text == "passed" || text == "success" ) {
293+ style .setFillForegroundColor (IndexedColors .BRIGHT_GREEN .getIndex ());
294+ }
295+ if (text == "fail" || text == "failed" || text == "failure" ) {
296+ style .setFillForegroundColor (IndexedColors .RED .getIndex ());
297+ }
298+ style .setFillPattern (FillPatternType .NO_FILL );
299+ style .setAlignment (HorizontalAlignment .CENTER );
300+ style .setVerticalAlignment (VerticalAlignment .CENTER );
301+
302+ cell .setCellStyle (style );
303+
304+ fileOut = new FileOutputStream (excelFilePath );
305+ workbook .write (fileOut );
306+ fileOut .flush ();
307+ fileOut .close ();
308+ } catch (Exception e ) {
309+ e .getMessage ();
310+ System .out .println (e .getMessage ());
311+ }
312+ }
313+
314+ public void setCellData (String text , int rowNumber , String columnName ) {
315+ try {
316+ row = sheet .getRow (rowNumber );
317+ if (row == null ) {
318+ row = sheet .createRow (rowNumber );
319+ }
320+ cell = row .getCell (columns .get (columnName ));
321+
322+ if (cell == null ) {
323+ cell = row .createCell (columns .get (columnName ));
324+ }
325+ cell .setCellValue (text );
326+
327+ XSSFCellStyle style = (XSSFCellStyle ) workbook .createCellStyle ();
328+ text = text .trim ().toLowerCase ();
329+ if (text == "pass" || text == "passed" || text == "success" ) {
330+ style .setFillForegroundColor (IndexedColors .BRIGHT_GREEN .getIndex ());
331+ }
332+ if (text == "fail" || text == "failed" || text == "failure" ) {
333+ style .setFillForegroundColor (IndexedColors .RED .getIndex ());
334+ }
335+
336+ style .setFillPattern (FillPatternType .NO_FILL );
337+ style .setAlignment (HorizontalAlignment .CENTER );
338+ style .setVerticalAlignment (VerticalAlignment .CENTER );
339+
340+ cell .setCellStyle (style );
341+
342+ fileOut = new FileOutputStream (excelFilePath );
343+ workbook .write (fileOut );
344+ fileOut .flush ();
345+ fileOut .close ();
346+
347+ System .out .println ("Write data to excel file successfully." );
348+
349+ } catch (Exception e ) {
350+ e .getMessage ();
351+ System .out .println (e .getMessage ());
352+ }
353+ }
354+
355+ }
0 commit comments