├── .github └── workflows │ └── maven.yml ├── .gitignore ├── README.md ├── pom.xml ├── src ├── main │ └── java │ │ └── com │ │ └── navlabs │ │ └── excel │ │ └── reader │ │ ├── NALExcelReader.java │ │ └── NALExcelXLSReader.java └── test │ └── java │ └── com │ └── tests │ └── ExcelPOITest.java ├── testdata.xls ├── testdata.xlsx ├── xls_reader.iml └── ~$testdata.xlsx /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Java CI with Maven 10 | 11 | on: 12 | push: 13 | branches: [ "master" ] 14 | pull_request: 15 | branches: [ "master" ] 16 | 17 | jobs: 18 | build: 19 | 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Set up JDK 11 25 | uses: actions/setup-java@v3 26 | with: 27 | java-version: '11' 28 | distribution: 'temurin' 29 | cache: maven 30 | - name: Build with Maven 31 | run: mvn -B package --file pom.xml 32 | 33 | # Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive 34 | - name: Update dependency graph 35 | uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ExcelUtil 2 | An excel utility for Excel read and write operations. 3 | 4 | This is a Java class that allows reading data from an Excel (.xlsx) file. It provides methods for getting the row count and cell data of a specific sheet. 5 | 6 | The class uses the Apache POI library for working with Excel files. It has a constructor that takes the path of the Excel file as a parameter and initializes the workbook object. 7 | 8 | The class has two methods for getting cell data, one that takes the sheet name and column name as parameters, and another that takes the sheet name and column number as parameters. Both methods also require the row number as a parameter. 9 | 10 | The class uses the Apache POI library's cell object to get the data from the cell. It handles different types of cell data such as string, numeric, formula, and date. 11 | 12 | The class also has a method for getting the row count of a specific sheet. It takes the sheet name as a parameter and uses the workbook object to get the sheet index and then returns the number of rows in the sheet. 13 | 14 | 15 | Here is a more detailed description of each method in the provided code: 16 | 17 | **public NALExcelXLSReader(String path)**: 18 | This is the constructor of the NALExcelXLSReader class. 19 | It takes a file path as input and initializes the instance variables path, fis, workbook, sheet, row, and cell. 20 | It also reads the workbook from the given file path using a FileInputStream and initializes the workbook and sheet instance variables to the first sheet of the workbook. 21 | 22 | **public int getRowCount(String sheetName)**: 23 | This method takes a sheet name as input and returns the number of rows in the sheet. 24 | It first gets the index of the sheet using the workbook.getSheetIndex(sheetName) method. 25 | If the sheet doesn't exist, it returns 0. Otherwise, it gets the sheet using workbook.getSheetAt(index) and returns the number of rows in the sheet using sheet.getLastRowNum() + 1. 26 | 27 | **public String getCellData(String sheetName, String colName, int rowNum)**: 28 | This method takes a sheet name, column name, and row number as input and returns the data in the cell corresponding to the input parameters. 29 | It first gets the index of the sheet using the workbook.getSheetIndex(sheetName) method. 30 | If the sheet doesn't exist, it returns an empty string. 31 | Otherwise, it searches for the column number corresponding to the input column name by iterating over the first row of the sheet. 32 | If the column doesn't exist, it returns an empty string. Otherwise, it gets the cell using row.getCell(col_Num) and returns the cell data as a string. 33 | If the cell is a string, it returns the string value. 34 | If the cell is a number or formula, it returns the numeric value as a string. 35 | If the cell is a blank, it returns an empty string. 36 | If the cell is a boolean, it returns the boolean value as a string. 37 | 38 | **public String getCellData(String sheetName, int colNum, int rowNum)**: 39 | This method takes a sheet name, column number, and row number as input and returns the data in the cell corresponding to the input parameters. 40 | It first gets the index of the sheet using the workbook.getSheetIndex(sheetName) method. 41 | If the sheet doesn't exist, it returns an empty string. Otherwise, it gets the cell using row.getCell(colNum) and returns the cell data as a string. 42 | If the cell is a string, it returns the string value. 43 | If the cell is a number or formula, it returns the numeric value as a string. 44 | If the cell is a blank, it returns an empty string. If the cell is a boolean, it returns the boolean value as a string. 45 | 46 | Note that both getCellData methods throw an exception and return an error message if the row or column doesn't exist in the sheet. 47 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | 6 | com.naveenautomationlabs.excel.reader 7 | xls_reader 8 | 1.0 9 | jar 10 | 11 | xls_reader 12 | An excel utility for Excel read and write operations 13 | http://maven.apache.org 14 | 15 | 16 | 17 | The Apache Software License, Version 2.0 18 | http://www.apache.org/licenses/LICENSE-2.0.txt 19 | 20 | 21 | 22 | 23 | scm:git:git://github.com/naveenanimation20/ExcelUtil.git 24 | scm:git:ssh://github.com/naveenanimation20/ExcelUtil.git 25 | https://github.com/naveenanimation20/ExcelUtil/tree/master 26 | 27 | 28 | 29 | 30 | Naveen Khunteta 31 | naveenanimation20@gmail.com 32 | Naveen AutomationLabs 33 | http://www.naveenautomationlabs.com 34 | 35 | 36 | 37 | 38 | UTF-8 39 | 1.8 40 | 1.8 41 | 42 | 43 | 44 | 45 | junit 46 | junit 47 | 3.8.1 48 | test 49 | 50 | 51 | 52 | org.apache.poi 53 | poi 54 | 5.2.3 55 | 56 | 57 | org.apache.poi 58 | poi-ooxml 59 | 5.2.3 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | org.apache.maven.plugins 68 | maven-source-plugin 69 | 2.2.1 70 | 71 | 72 | attach-sources 73 | 74 | jar-no-fork 75 | 76 | 77 | 78 | 79 | 80 | org.apache.maven.plugins 81 | maven-javadoc-plugin 82 | 2.9.1 83 | 84 | 85 | attach-javadocs 86 | 87 | jar 88 | 89 | 90 | 91 | 92 | 93 | org.apache.maven.plugins 94 | maven-gpg-plugin 95 | 1.5 96 | 97 | 98 | sign-artifacts 99 | verify 100 | 101 | sign 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /src/main/java/com/navlabs/excel/reader/NALExcelReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * author: Naveen Khunteta 3 | * This NALExcelReader util class can be used to read/write with .xls format only. It won't work with .xlsx extension. 4 | */ 5 | 6 | package com.navlabs.excel.reader; 7 | 8 | import java.io.FileInputStream; 9 | import java.io.FileNotFoundException; 10 | import java.io.FileOutputStream; 11 | import java.io.IOException; 12 | import java.util.Calendar; 13 | 14 | import org.apache.poi.common.usermodel.HyperlinkType; 15 | import org.apache.poi.hssf.usermodel.HSSFCell; 16 | import org.apache.poi.hssf.usermodel.HSSFCellStyle; 17 | import org.apache.poi.hssf.usermodel.HSSFCreationHelper; 18 | import org.apache.poi.hssf.usermodel.HSSFFont; 19 | import org.apache.poi.hssf.usermodel.HSSFHyperlink; 20 | import org.apache.poi.hssf.usermodel.HSSFRow; 21 | import org.apache.poi.hssf.usermodel.HSSFSheet; 22 | import org.apache.poi.hssf.usermodel.HSSFWorkbook; 23 | import org.apache.poi.hssf.util.HSSFColor; 24 | import org.apache.poi.ss.usermodel.CellStyle; 25 | import org.apache.poi.ss.usermodel.CellType; 26 | import org.apache.poi.ss.usermodel.DateUtil; 27 | import org.apache.poi.ss.usermodel.FillPatternType; 28 | import org.apache.poi.ss.usermodel.IndexedColors; 29 | import org.apache.poi.ss.usermodel.Sheet; 30 | import org.apache.poi.ss.usermodel.Workbook; 31 | import org.apache.poi.ss.usermodel.WorkbookFactory; 32 | 33 | 34 | /* 35 | * ################# This NALExcelReader util class can be used to read/write with .xls format only. ######### 36 | * ############################### It won't work with .xlsx extension ################################ 37 | */ 38 | public class NALExcelReader { 39 | 40 | public String path; 41 | public FileInputStream fis = null; 42 | public FileOutputStream fileOut = null; 43 | private HSSFWorkbook workbook = null; 44 | private HSSFSheet sheet = null; 45 | private HSSFRow row = null; 46 | private HSSFCell cell = null; 47 | 48 | public NALExcelReader(String path) { 49 | 50 | this.path = path; 51 | try { 52 | 53 | fis = new FileInputStream(path); 54 | workbook = new HSSFWorkbook(fis); 55 | sheet = workbook.getSheetAt(0); 56 | fis.close(); 57 | } catch (Exception e) { 58 | // TODO Auto-generated catch block 59 | e.printStackTrace(); 60 | } 61 | } 62 | // returns the row count in a sheet 63 | 64 | public int getRowCount(String sheetName) { 65 | int index = workbook.getSheetIndex(sheetName); 66 | if (index == -1) 67 | return 0; 68 | else { 69 | sheet = workbook.getSheetAt(index); 70 | int number = sheet.getLastRowNum() + 1; 71 | return number; 72 | } 73 | 74 | } 75 | // returns the data from a cell 76 | 77 | public String getCellData(String sheetName, String colName, int rowNum) { 78 | try { 79 | if (rowNum <= 0) 80 | return ""; 81 | 82 | int index = workbook.getSheetIndex(sheetName); 83 | int col_Num = -1; 84 | if (index == -1) 85 | return ""; 86 | 87 | sheet = workbook.getSheetAt(index); 88 | row = sheet.getRow(0); 89 | for (int i = 0; i < row.getLastCellNum(); i++) { 90 | // System.out.println(row.getCell(i).getStringCellValue().trim()); 91 | if (row.getCell(i).getStringCellValue().trim().equals(colName.trim())) 92 | col_Num = i; 93 | } 94 | if (col_Num == -1) 95 | return ""; 96 | 97 | sheet = workbook.getSheetAt(index); 98 | row = sheet.getRow(rowNum - 1); 99 | if (row == null) 100 | return ""; 101 | cell = row.getCell(col_Num); 102 | 103 | if (cell == null) 104 | return ""; 105 | // System.out.println(cell.getCellType()); 106 | if (cell.getCellType() == CellType.STRING) 107 | return cell.getStringCellValue(); 108 | else if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) { 109 | 110 | String cellText = String.valueOf(cell.getNumericCellValue()); 111 | if (DateUtil.isCellDateFormatted(cell)) { 112 | 113 | // format in form of M/D/YY 114 | double d = cell.getNumericCellValue(); 115 | 116 | Calendar cal = Calendar.getInstance(); 117 | cal.setTime(DateUtil.getJavaDate(d)); 118 | cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2); 119 | cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" + cal.get(Calendar.MONTH) + 1 + "/" + cellText; 120 | 121 | // System.out.println(cellText); 122 | 123 | } 124 | 125 | return cellText; 126 | } else if (cell.getCellType() == CellType.BLANK) 127 | return ""; 128 | else 129 | return String.valueOf(cell.getBooleanCellValue()); 130 | 131 | } catch (Exception e) { 132 | 133 | e.printStackTrace(); 134 | return "row " + rowNum + " or column " + colName + " does not exist in xls"; 135 | } 136 | } 137 | 138 | // returns the data from a cell 139 | public String getCellData(String sheetName, int colNum, int rowNum) { 140 | try { 141 | if (rowNum <= 0) 142 | return ""; 143 | 144 | int index = workbook.getSheetIndex(sheetName); 145 | 146 | if (index == -1) 147 | return ""; 148 | 149 | sheet = workbook.getSheetAt(index); 150 | row = sheet.getRow(rowNum - 1); 151 | if (row == null) 152 | return ""; 153 | cell = row.getCell(colNum); 154 | if (cell == null) 155 | return ""; 156 | 157 | if (cell.getCellType() == CellType.STRING) 158 | return cell.getStringCellValue(); 159 | else if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) { 160 | 161 | String cellText = String.valueOf(cell.getNumericCellValue()); 162 | if (DateUtil.isCellDateFormatted(cell)) { 163 | // format in form of M/D/YY 164 | double d = cell.getNumericCellValue(); 165 | 166 | Calendar cal = Calendar.getInstance(); 167 | cal.setTime(DateUtil.getJavaDate(d)); 168 | cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2); 169 | cellText = cal.get(Calendar.MONTH) + 1 + "/" + cal.get(Calendar.DAY_OF_MONTH) + "/" + cellText; 170 | 171 | // System.out.println(cellText); 172 | 173 | } 174 | 175 | return cellText; 176 | } else if (cell.getCellType() == CellType.BLANK) 177 | return ""; 178 | else 179 | return String.valueOf(cell.getBooleanCellValue()); 180 | } catch (Exception e) { 181 | 182 | e.printStackTrace(); 183 | return "row " + rowNum + " or column " + colNum + " does not exist in xls"; 184 | } 185 | } 186 | 187 | // returns true if data is set successfully else false 188 | public boolean setCellData(String sheetName, String colName, int rowNum, String data) { 189 | try { 190 | fis = new FileInputStream(path); 191 | workbook = new HSSFWorkbook(fis); 192 | 193 | if (rowNum <= 0) 194 | return false; 195 | 196 | int index = workbook.getSheetIndex(sheetName); 197 | int colNum = -1; 198 | if (index == -1) 199 | return false; 200 | 201 | sheet = workbook.getSheetAt(index); 202 | 203 | row = sheet.getRow(0); 204 | for (int i = 0; i < row.getLastCellNum(); i++) { 205 | // System.out.println(row.getCell(i).getStringCellValue().trim()); 206 | if (row.getCell(i).getStringCellValue().trim().equals(colName)) 207 | colNum = i; 208 | } 209 | if (colNum == -1) 210 | return false; 211 | 212 | sheet.autoSizeColumn(colNum); 213 | row = sheet.getRow(rowNum - 1); 214 | if (row == null) 215 | row = sheet.createRow(rowNum - 1); 216 | 217 | cell = row.getCell(colNum); 218 | if (cell == null) 219 | cell = row.createCell(colNum); 220 | 221 | // cell style 222 | // CellStyle cs = workbook.createCellStyle(); 223 | // cs.setWrapText(true); 224 | // cell.setCellStyle(cs); 225 | cell.setCellValue(data); 226 | 227 | fileOut = new FileOutputStream(path); 228 | 229 | workbook.write(fileOut); 230 | 231 | fileOut.close(); 232 | 233 | } catch (Exception e) { 234 | e.printStackTrace(); 235 | return false; 236 | } 237 | return true; 238 | } 239 | 240 | // returns true if data is set successfully else false 241 | public boolean setCellData(String sheetName, String colName, int rowNum, String data, String url) { 242 | // System.out.println("setCellData setCellData******************"); 243 | try { 244 | fis = new FileInputStream(path); 245 | workbook = new HSSFWorkbook(fis); 246 | 247 | if (rowNum <= 0) 248 | return false; 249 | 250 | int index = workbook.getSheetIndex(sheetName); 251 | int colNum = -1; 252 | if (index == -1) 253 | return false; 254 | 255 | sheet = workbook.getSheetAt(index); 256 | // System.out.println("A"); 257 | row = sheet.getRow(0); 258 | for (int i = 0; i < row.getLastCellNum(); i++) { 259 | // System.out.println(row.getCell(i).getStringCellValue().trim()); 260 | if (row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName)) 261 | colNum = i; 262 | } 263 | 264 | if (colNum == -1) 265 | return false; 266 | sheet.autoSizeColumn(colNum); // ashish 267 | row = sheet.getRow(rowNum - 1); 268 | if (row == null) 269 | row = sheet.createRow(rowNum - 1); 270 | 271 | cell = row.getCell(colNum); 272 | if (cell == null) 273 | cell = row.createCell(colNum); 274 | 275 | cell.setCellValue(data); 276 | HSSFCreationHelper createHelper = workbook.getCreationHelper(); 277 | 278 | // cell style for hyperlinks 279 | // by default hypelrinks are blue and underlined 280 | CellStyle hlink_style = workbook.createCellStyle(); 281 | HSSFFont hlink_font = workbook.createFont(); 282 | hlink_font.setUnderline(HSSFFont.U_SINGLE); 283 | hlink_font.setColor(IndexedColors.BLUE.getIndex()); 284 | hlink_style.setFont(hlink_font); 285 | // hlink_style.setWrapText(true); 286 | 287 | HSSFHyperlink link = createHelper.createHyperlink(HyperlinkType.FILE); 288 | link.setAddress(url); 289 | cell.setHyperlink(link); 290 | cell.setCellStyle(hlink_style); 291 | 292 | fileOut = new FileOutputStream(path); 293 | workbook.write(fileOut); 294 | 295 | fileOut.close(); 296 | 297 | } catch (Exception e) { 298 | e.printStackTrace(); 299 | return false; 300 | } 301 | return true; 302 | } 303 | 304 | // returns true if sheet is created successfully else false 305 | public boolean addSheet(String sheetname) { 306 | 307 | FileOutputStream fileOut; 308 | try { 309 | workbook.createSheet(sheetname); 310 | fileOut = new FileOutputStream(path); 311 | workbook.write(fileOut); 312 | fileOut.close(); 313 | } catch (Exception e) { 314 | e.printStackTrace(); 315 | return false; 316 | } 317 | return true; 318 | } 319 | 320 | // returns true if sheet is removed successfully else false if sheet does 321 | // not exist 322 | public boolean removeSheet(String sheetName) { 323 | int index = workbook.getSheetIndex(sheetName); 324 | if (index == -1) 325 | return false; 326 | 327 | FileOutputStream fileOut; 328 | try { 329 | workbook.removeSheetAt(index); 330 | fileOut = new FileOutputStream(path); 331 | workbook.write(fileOut); 332 | fileOut.close(); 333 | } catch (Exception e) { 334 | e.printStackTrace(); 335 | return false; 336 | } 337 | return true; 338 | } 339 | 340 | // returns true if column is created successfully 341 | public boolean addColumn(String sheetName, String colName) { 342 | // System.out.println("**************addColumn*********************"); 343 | 344 | try { 345 | fis = new FileInputStream(path); 346 | workbook = new HSSFWorkbook(fis); 347 | int index = workbook.getSheetIndex(sheetName); 348 | if (index == -1) 349 | return false; 350 | 351 | HSSFCellStyle style = workbook.createCellStyle(); 352 | style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_40_PERCENT.getIndex()); 353 | style.setFillPattern(FillPatternType.SOLID_FOREGROUND); 354 | 355 | sheet = workbook.getSheetAt(index); 356 | 357 | row = sheet.getRow(0); 358 | if (row == null) 359 | row = sheet.createRow(0); 360 | 361 | // cell = row.getCell(); 362 | // if (cell == null) 363 | // System.out.println(row.getLastCellNum()); 364 | if (row.getLastCellNum() == -1) 365 | cell = row.createCell(0); 366 | else 367 | cell = row.createCell(row.getLastCellNum()); 368 | 369 | cell.setCellValue(colName); 370 | cell.setCellStyle(style); 371 | 372 | fileOut = new FileOutputStream(path); 373 | workbook.write(fileOut); 374 | fileOut.close(); 375 | 376 | } catch (Exception e) { 377 | e.printStackTrace(); 378 | return false; 379 | } 380 | 381 | return true; 382 | 383 | } 384 | 385 | // removes a column and all the contents 386 | public boolean removeColumn(String sheetName, int colNum) { 387 | try { 388 | if (!isSheetExist(sheetName)) 389 | return false; 390 | fis = new FileInputStream(path); 391 | workbook = new HSSFWorkbook(fis); 392 | sheet = workbook.getSheet(sheetName); 393 | HSSFCellStyle style = workbook.createCellStyle(); 394 | style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_40_PERCENT.getIndex()); 395 | //HSSFCreationHelper createHelper = workbook.getCreationHelper(); 396 | style.setFillPattern(FillPatternType.NO_FILL); 397 | 398 | for (int i = 0; i < getRowCount(sheetName); i++) { 399 | row = sheet.getRow(i); 400 | if (row != null) { 401 | cell = row.getCell(colNum); 402 | if (cell != null) { 403 | cell.setCellStyle(style); 404 | row.removeCell(cell); 405 | } 406 | } 407 | } 408 | fileOut = new FileOutputStream(path); 409 | workbook.write(fileOut); 410 | fileOut.close(); 411 | } catch (Exception e) { 412 | e.printStackTrace(); 413 | return false; 414 | } 415 | return true; 416 | 417 | } 418 | 419 | // find whether sheets exists 420 | public boolean isSheetExist(String sheetName) { 421 | int index = workbook.getSheetIndex(sheetName); 422 | if (index == -1) { 423 | index = workbook.getSheetIndex(sheetName.toUpperCase()); 424 | if (index == -1) 425 | return false; 426 | else 427 | return true; 428 | } else 429 | return true; 430 | } 431 | 432 | // returns number of columns in a sheet 433 | public int getColumnCount(String sheetName) { 434 | // check if sheet exists 435 | if (!isSheetExist(sheetName)) 436 | return -1; 437 | 438 | sheet = workbook.getSheet(sheetName); 439 | row = sheet.getRow(0); 440 | 441 | if (row == null) 442 | return -1; 443 | 444 | return row.getLastCellNum(); 445 | 446 | } 447 | 448 | // String sheetName, String testCaseName,String keyword ,String URL,String 449 | // message 450 | public boolean addHyperLink(String sheetName, String screenShotColName, String testCaseName, int index, String url, 451 | String message) { 452 | // System.out.println("ADDING addHyperLink******************"); 453 | 454 | url = url.replace('\\', '/'); 455 | if (!isSheetExist(sheetName)) 456 | return false; 457 | 458 | sheet = workbook.getSheet(sheetName); 459 | 460 | for (int i = 2; i <= getRowCount(sheetName); i++) { 461 | if (getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)) { 462 | // System.out.println("**caught "+(i+index)); 463 | setCellData(sheetName, screenShotColName, i + index, message, url); 464 | break; 465 | } 466 | } 467 | 468 | return true; 469 | } 470 | 471 | public int getCellRowNum(String sheetName, String colName, String cellValue) { 472 | 473 | for (int i = 2; i <= getRowCount(sheetName); i++) { 474 | if (getCellData(sheetName, colName, i).equalsIgnoreCase(cellValue)) { 475 | return i; 476 | } 477 | } 478 | return -1; 479 | 480 | } 481 | 482 | /** 483 | * Read all rows and columns and return 2D Object array: can be used with testNG dataprovider. 484 | * @param sheetName 485 | * @return 486 | */ 487 | public Object[][] getSheetData(String sheetName) { 488 | Workbook book; 489 | Sheet sheet = null; 490 | 491 | Object data[][] = null; 492 | try { 493 | FileInputStream ip = new FileInputStream(path); 494 | book = WorkbookFactory.create(ip); 495 | sheet = book.getSheet(sheetName); 496 | 497 | } catch (FileNotFoundException e) { 498 | e.printStackTrace(); 499 | } catch (IOException e) { 500 | e.printStackTrace(); 501 | } 502 | 503 | data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()]; 504 | 505 | for (int i = 0; i < sheet.getLastRowNum(); i++) { 506 | for (int j = 0; j < sheet.getRow(0).getLastCellNum(); j++) { 507 | data[i][j] = sheet.getRow(i + 1).getCell(j).toString(); 508 | } 509 | } 510 | 511 | return data; 512 | } 513 | 514 | } 515 | -------------------------------------------------------------------------------- /src/main/java/com/navlabs/excel/reader/NALExcelXLSReader.java: -------------------------------------------------------------------------------- 1 | package com.navlabs.excel.reader; 2 | 3 | /* 4 | * author: Naveen Khunteta 5 | */ 6 | 7 | import java.io.FileInputStream; 8 | import java.io.FileNotFoundException; 9 | import java.io.FileOutputStream; 10 | import java.io.IOException; 11 | import java.util.Calendar; 12 | 13 | import org.apache.poi.common.usermodel.HyperlinkType; 14 | import org.apache.poi.hssf.usermodel.HSSFFont; 15 | import org.apache.poi.hssf.util.HSSFColor; 16 | import org.apache.poi.ss.usermodel.CellStyle; 17 | import org.apache.poi.ss.usermodel.CellType; 18 | import org.apache.poi.ss.usermodel.DateUtil; 19 | import org.apache.poi.ss.usermodel.FillPatternType; 20 | import org.apache.poi.ss.usermodel.IndexedColors; 21 | import org.apache.poi.ss.usermodel.Sheet; 22 | import org.apache.poi.ss.usermodel.Workbook; 23 | import org.apache.poi.ss.usermodel.WorkbookFactory; 24 | import org.apache.poi.xssf.usermodel.XSSFCell; 25 | import org.apache.poi.xssf.usermodel.XSSFCellStyle; 26 | import org.apache.poi.xssf.usermodel.XSSFCreationHelper; 27 | import org.apache.poi.xssf.usermodel.XSSFFont; 28 | import org.apache.poi.xssf.usermodel.XSSFHyperlink; 29 | import org.apache.poi.xssf.usermodel.XSSFRow; 30 | import org.apache.poi.xssf.usermodel.XSSFSheet; 31 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 32 | 33 | /* 34 | * ################# This NALExcelReader util class can be used to read/write with .xlsx format only. ######### 35 | * ############################### It won't work with .xls extension ################################ 36 | */ 37 | public class NALExcelXLSReader { 38 | 39 | public String path; 40 | public FileInputStream fis = null; 41 | public FileOutputStream fileOut = null; 42 | private XSSFWorkbook workbook = null; 43 | private XSSFSheet sheet = null; 44 | private XSSFRow row = null; 45 | private XSSFCell cell = null; 46 | 47 | public NALExcelXLSReader(String path) { 48 | 49 | this.path = path; 50 | try { 51 | 52 | fis = new FileInputStream(path); 53 | workbook = new XSSFWorkbook(fis); 54 | sheet = workbook.getSheetAt(0); 55 | fis.close(); 56 | } catch (Exception e) { 57 | // TODO Auto-generated catch block 58 | e.printStackTrace(); 59 | } 60 | } 61 | 62 | /** 63 | * returns the row count in a sheet 64 | * @param sheetName 65 | * @return 66 | */ 67 | public int getRowCount(String sheetName) { 68 | int index = workbook.getSheetIndex(sheetName); 69 | if (index == -1) 70 | return 0; 71 | else { 72 | sheet = workbook.getSheetAt(index); 73 | int number = sheet.getLastRowNum() + 1; 74 | return number; 75 | } 76 | 77 | } 78 | 79 | /** 80 | * returns the data from a cell 81 | * @param sheetName 82 | * @param colName 83 | * @param rowNum 84 | * @return 85 | */ 86 | public String getCellData(String sheetName, String colName, int rowNum) { 87 | try { 88 | if (rowNum <= 0) 89 | return ""; 90 | 91 | int index = workbook.getSheetIndex(sheetName); 92 | int col_Num = -1; 93 | if (index == -1) 94 | return ""; 95 | 96 | sheet = workbook.getSheetAt(index); 97 | row = sheet.getRow(0); 98 | for (int i = 0; i < row.getLastCellNum(); i++) { 99 | // System.out.println(row.getCell(i).getStringCellValue().trim()); 100 | if (row.getCell(i).getStringCellValue().trim().equals(colName.trim())) 101 | col_Num = i; 102 | } 103 | if (col_Num == -1) 104 | return ""; 105 | 106 | sheet = workbook.getSheetAt(index); 107 | row = sheet.getRow(rowNum - 1); 108 | if (row == null) 109 | return ""; 110 | cell = row.getCell(col_Num); 111 | 112 | if (cell == null) 113 | return ""; 114 | // System.out.println(cell.getCellType()); 115 | if (cell.getCellType() == CellType.STRING) 116 | return cell.getStringCellValue(); 117 | else if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) { 118 | 119 | String cellText = String.valueOf(cell.getNumericCellValue()); 120 | if (DateUtil.isCellDateFormatted(cell)) { 121 | 122 | // format in form of M/D/YY 123 | double d = cell.getNumericCellValue(); 124 | 125 | Calendar cal = Calendar.getInstance(); 126 | cal.setTime(DateUtil.getJavaDate(d)); 127 | cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2); 128 | cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" + cal.get(Calendar.MONTH) + 1 + "/" + cellText; 129 | 130 | // System.out.println(cellText); 131 | 132 | } 133 | 134 | return cellText; 135 | } else if (cell.getCellType() == CellType.BLANK) 136 | return ""; 137 | else 138 | return String.valueOf(cell.getBooleanCellValue()); 139 | 140 | } catch (Exception e) { 141 | 142 | e.printStackTrace(); 143 | return "row " + rowNum + " or column " + colName + " does not exist in xls"; 144 | } 145 | } 146 | 147 | /** 148 | * returns the data from a cell 149 | * @param sheetName 150 | * @param colNum 151 | * @param rowNum 152 | * @return 153 | */ 154 | public String getCellData(String sheetName, int colNum, int rowNum) { 155 | try { 156 | if (rowNum <= 0) 157 | return ""; 158 | 159 | int index = workbook.getSheetIndex(sheetName); 160 | 161 | if (index == -1) 162 | return ""; 163 | 164 | sheet = workbook.getSheetAt(index); 165 | row = sheet.getRow(rowNum - 1); 166 | if (row == null) 167 | return ""; 168 | cell = row.getCell(colNum); 169 | if (cell == null) 170 | return ""; 171 | 172 | if (cell.getCellType() == CellType.STRING) 173 | return cell.getStringCellValue(); 174 | else if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) { 175 | 176 | String cellText = String.valueOf(cell.getNumericCellValue()); 177 | if (DateUtil.isCellDateFormatted(cell)) { 178 | // format in form of M/D/YY 179 | double d = cell.getNumericCellValue(); 180 | 181 | Calendar cal = Calendar.getInstance(); 182 | cal.setTime(DateUtil.getJavaDate(d)); 183 | cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2); 184 | cellText = cal.get(Calendar.MONTH) + 1 + "/" + cal.get(Calendar.DAY_OF_MONTH) + "/" + cellText; 185 | 186 | // System.out.println(cellText); 187 | 188 | } 189 | 190 | return cellText; 191 | } else if (cell.getCellType() == CellType.BLANK) 192 | return ""; 193 | else 194 | return String.valueOf(cell.getBooleanCellValue()); 195 | } catch (Exception e) { 196 | 197 | e.printStackTrace(); 198 | return "row " + rowNum + " or column " + colNum + " does not exist in xls"; 199 | } 200 | } 201 | 202 | /** 203 | * returns true if data is set successfully else false 204 | * @param sheetName 205 | * @param colName 206 | * @param rowNum 207 | * @param data 208 | * @return 209 | */ 210 | public boolean setCellData(String sheetName, String colName, int rowNum, String data) { 211 | try { 212 | fis = new FileInputStream(path); 213 | workbook = new XSSFWorkbook(fis); 214 | 215 | if (rowNum <= 0) 216 | return false; 217 | 218 | int index = workbook.getSheetIndex(sheetName); 219 | int colNum = -1; 220 | if (index == -1) 221 | return false; 222 | 223 | sheet = workbook.getSheetAt(index); 224 | 225 | row = sheet.getRow(0); 226 | for (int i = 0; i < row.getLastCellNum(); i++) { 227 | // System.out.println(row.getCell(i).getStringCellValue().trim()); 228 | if (row.getCell(i).getStringCellValue().trim().equals(colName)) 229 | colNum = i; 230 | } 231 | if (colNum == -1) 232 | return false; 233 | 234 | sheet.autoSizeColumn(colNum); 235 | row = sheet.getRow(rowNum - 1); 236 | if (row == null) 237 | row = sheet.createRow(rowNum - 1); 238 | 239 | cell = row.getCell(colNum); 240 | if (cell == null) 241 | cell = row.createCell(colNum); 242 | 243 | // cell style 244 | // CellStyle cs = workbook.createCellStyle(); 245 | // cs.setWrapText(true); 246 | // cell.setCellStyle(cs); 247 | cell.setCellValue(data); 248 | 249 | fileOut = new FileOutputStream(path); 250 | 251 | workbook.write(fileOut); 252 | 253 | fileOut.close(); 254 | 255 | } catch (Exception e) { 256 | e.printStackTrace(); 257 | return false; 258 | } 259 | return true; 260 | } 261 | 262 | 263 | /** 264 | * returns true if data is set successfully else false 265 | * @param sheetName 266 | * @param colName 267 | * @param rowNum 268 | * @param data 269 | * @param url 270 | * @return 271 | */ 272 | public boolean setCellData(String sheetName, String colName, int rowNum, String data, String url) { 273 | // System.out.println("setCellData setCellData******************"); 274 | try { 275 | fis = new FileInputStream(path); 276 | workbook = new XSSFWorkbook(fis); 277 | 278 | if (rowNum <= 0) 279 | return false; 280 | 281 | int index = workbook.getSheetIndex(sheetName); 282 | int colNum = -1; 283 | if (index == -1) 284 | return false; 285 | 286 | sheet = workbook.getSheetAt(index); 287 | // System.out.println("A"); 288 | row = sheet.getRow(0); 289 | for (int i = 0; i < row.getLastCellNum(); i++) { 290 | // System.out.println(row.getCell(i).getStringCellValue().trim()); 291 | if (row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName)) 292 | colNum = i; 293 | } 294 | 295 | if (colNum == -1) 296 | return false; 297 | sheet.autoSizeColumn(colNum); // ashish 298 | row = sheet.getRow(rowNum - 1); 299 | if (row == null) 300 | row = sheet.createRow(rowNum - 1); 301 | 302 | cell = row.getCell(colNum); 303 | if (cell == null) 304 | cell = row.createCell(colNum); 305 | 306 | cell.setCellValue(data); 307 | XSSFCreationHelper createHelper = workbook.getCreationHelper(); 308 | 309 | // cell style for hyperlinks 310 | // by default hypelrinks are blue and underlined 311 | CellStyle hlink_style = workbook.createCellStyle(); 312 | XSSFFont hlink_font = workbook.createFont(); 313 | hlink_font.setUnderline(HSSFFont.U_SINGLE); 314 | hlink_font.setColor(IndexedColors.BLUE.getIndex()); 315 | hlink_style.setFont(hlink_font); 316 | // hlink_style.setWrapText(true); 317 | 318 | XSSFHyperlink link = createHelper.createHyperlink(HyperlinkType.FILE); 319 | link.setAddress(url); 320 | cell.setHyperlink(link); 321 | cell.setCellStyle(hlink_style); 322 | 323 | fileOut = new FileOutputStream(path); 324 | workbook.write(fileOut); 325 | 326 | fileOut.close(); 327 | 328 | } catch (Exception e) { 329 | e.printStackTrace(); 330 | return false; 331 | } 332 | return true; 333 | } 334 | 335 | /** 336 | * returns true if sheet is created successfully else false 337 | * @param sheetname 338 | * @return 339 | */ 340 | public boolean addSheet(String sheetname) { 341 | 342 | FileOutputStream fileOut; 343 | try { 344 | workbook.createSheet(sheetname); 345 | fileOut = new FileOutputStream(path); 346 | workbook.write(fileOut); 347 | fileOut.close(); 348 | } catch (Exception e) { 349 | e.printStackTrace(); 350 | return false; 351 | } 352 | return true; 353 | } 354 | 355 | /** 356 | * returns true if sheet is removed successfully else false if sheet does not exist 357 | * @param sheetName 358 | * @return 359 | */ 360 | public boolean removeSheet(String sheetName) { 361 | int index = workbook.getSheetIndex(sheetName); 362 | if (index == -1) 363 | return false; 364 | 365 | FileOutputStream fileOut; 366 | try { 367 | workbook.removeSheetAt(index); 368 | fileOut = new FileOutputStream(path); 369 | workbook.write(fileOut); 370 | fileOut.close(); 371 | } catch (Exception e) { 372 | e.printStackTrace(); 373 | return false; 374 | } 375 | return true; 376 | } 377 | 378 | 379 | /** 380 | * returns true if column is created successfully 381 | * @param sheetName 382 | * @param colName 383 | * @return 384 | */ 385 | public boolean addColumn(String sheetName, String colName) { 386 | try { 387 | fis = new FileInputStream(path); 388 | workbook = new XSSFWorkbook(fis); 389 | int index = workbook.getSheetIndex(sheetName); 390 | if (index == -1) 391 | return false; 392 | 393 | XSSFCellStyle style = workbook.createCellStyle(); 394 | style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_40_PERCENT.getIndex()); 395 | style.setFillPattern(FillPatternType.SOLID_FOREGROUND); 396 | 397 | sheet = workbook.getSheetAt(index); 398 | 399 | row = sheet.getRow(0); 400 | if (row == null) 401 | row = sheet.createRow(0); 402 | 403 | if (row.getLastCellNum() == -1) 404 | cell = row.createCell(0); 405 | else 406 | cell = row.createCell(row.getLastCellNum()); 407 | 408 | cell.setCellValue(colName); 409 | cell.setCellStyle(style); 410 | 411 | fileOut = new FileOutputStream(path); 412 | workbook.write(fileOut); 413 | fileOut.close(); 414 | 415 | } catch (Exception e) { 416 | e.printStackTrace(); 417 | return false; 418 | } 419 | 420 | return true; 421 | 422 | } 423 | 424 | /** 425 | * removes a column and all the contents 426 | * @param sheetName 427 | * @param colNum 428 | * @return 429 | */ 430 | public boolean removeColumn(String sheetName, int colNum) { 431 | try { 432 | if (!isSheetExist(sheetName)) 433 | return false; 434 | fis = new FileInputStream(path); 435 | workbook = new XSSFWorkbook(fis); 436 | sheet = workbook.getSheet(sheetName); 437 | XSSFCellStyle style = workbook.createCellStyle(); 438 | style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_40_PERCENT.getIndex()); 439 | //XSSFCreationHelper createHelper = workbook.getCreationHelper(); 440 | style.setFillPattern(FillPatternType.NO_FILL); 441 | 442 | for (int i = 0; i < getRowCount(sheetName); i++) { 443 | row = sheet.getRow(i); 444 | if (row != null) { 445 | cell = row.getCell(colNum); 446 | if (cell != null) { 447 | cell.setCellStyle(style); 448 | row.removeCell(cell); 449 | } 450 | } 451 | } 452 | fileOut = new FileOutputStream(path); 453 | workbook.write(fileOut); 454 | fileOut.close(); 455 | } catch (Exception e) { 456 | e.printStackTrace(); 457 | return false; 458 | } 459 | return true; 460 | 461 | } 462 | 463 | 464 | /** 465 | * find whether sheets exists 466 | * @param sheetName 467 | * @return 468 | */ 469 | public boolean isSheetExist(String sheetName) { 470 | int index = workbook.getSheetIndex(sheetName); 471 | if (index == -1) { 472 | index = workbook.getSheetIndex(sheetName.toUpperCase()); 473 | if (index == -1) 474 | return false; 475 | else 476 | return true; 477 | } else 478 | return true; 479 | } 480 | 481 | 482 | /** 483 | * returns number of columns in a sheet 484 | * @param sheetName 485 | * @return 486 | */ 487 | public int getColumnCount(String sheetName) { 488 | // check if sheet exists 489 | if (!isSheetExist(sheetName)) 490 | return -1; 491 | 492 | sheet = workbook.getSheet(sheetName); 493 | row = sheet.getRow(0); 494 | 495 | if (row == null) 496 | return -1; 497 | 498 | return row.getLastCellNum(); 499 | 500 | } 501 | 502 | /** 503 | * add hyperlink in the sheet 504 | * @param sheetName 505 | * @param screenShotColName 506 | * @param testCaseName 507 | * @param index 508 | * @param url 509 | * @param message 510 | * @return 511 | */ 512 | public boolean addHyperLink(String sheetName, String screenShotColName, String testCaseName, int index, String url, 513 | String message) { 514 | 515 | url = url.replace('\\', '/'); 516 | if (!isSheetExist(sheetName)) 517 | return false; 518 | 519 | sheet = workbook.getSheet(sheetName); 520 | 521 | for (int i = 2; i <= getRowCount(sheetName); i++) { 522 | if (getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)) { 523 | setCellData(sheetName, screenShotColName, i + index, message, url); 524 | break; 525 | } 526 | } 527 | 528 | return true; 529 | } 530 | 531 | public int getCellRowNum(String sheetName, String colName, String cellValue) { 532 | 533 | for (int i = 2; i <= getRowCount(sheetName); i++) { 534 | if (getCellData(sheetName, colName, i).equalsIgnoreCase(cellValue)) { 535 | return i; 536 | } 537 | } 538 | return -1; 539 | 540 | } 541 | 542 | /** 543 | * Read all rows and columns and return 2D Object array: can be used with testNG dataprovider. 544 | * @param sheetName 545 | * @return 546 | */ 547 | public Object[][] getSheetData(String sheetName) { 548 | Workbook book; 549 | Sheet sheet = null; 550 | 551 | Object data[][] = null; 552 | try { 553 | FileInputStream ip = new FileInputStream(path); 554 | book = WorkbookFactory.create(ip); 555 | sheet = book.getSheet(sheetName); 556 | 557 | } catch (FileNotFoundException e) { 558 | e.printStackTrace(); 559 | } catch (IOException e) { 560 | e.printStackTrace(); 561 | } 562 | 563 | data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()]; 564 | 565 | for (int i = 0; i < sheet.getLastRowNum(); i++) { 566 | for (int j = 0; j < sheet.getRow(0).getLastCellNum(); j++) { 567 | data[i][j] = sheet.getRow(i + 1).getCell(j).toString(); 568 | } 569 | } 570 | 571 | return data; 572 | } 573 | 574 | } 575 | -------------------------------------------------------------------------------- /src/test/java/com/tests/ExcelPOITest.java: -------------------------------------------------------------------------------- 1 | package com.tests; 2 | 3 | import java.util.Arrays; 4 | 5 | import com.navlabs.excel.reader.NALExcelXLSReader; 6 | 7 | public class ExcelPOITest { 8 | 9 | public static void main(String[] args) { 10 | 11 | 12 | NALExcelXLSReader reader = new NALExcelXLSReader("testdata.xlsx"); 13 | int col = reader.getColumnCount("register"); 14 | System.out.println(col); 15 | 16 | String cell = reader.getCellData("register", "firstname", 2); 17 | System.out.println(cell); 18 | 19 | reader.addSheet("naveen"); 20 | 21 | Object data[][] = reader.getSheetData("register"); 22 | System.out.println(Arrays.deepToString(data)); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /testdata.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/naveenanimation20/ExcelUtil/61b6d243b3ce7c76d549ccba362542f211b8d406/testdata.xls -------------------------------------------------------------------------------- /testdata.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/naveenanimation20/ExcelUtil/61b6d243b3ce7c76d549ccba362542f211b8d406/testdata.xlsx -------------------------------------------------------------------------------- /xls_reader.iml: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /~$testdata.xlsx: -------------------------------------------------------------------------------- 1 | Naveen Naveen Naveen Naveen --------------------------------------------------------------------------------