1+ package com .baeldung .poi .excel ;
2+
3+ import java .io .File ;
4+ import java .io .FileInputStream ;
5+ import java .io .IOException ;
6+
7+ import org .apache .poi .ss .usermodel .Cell ;
8+ import org .apache .poi .ss .usermodel .CellType ;
9+ import org .apache .poi .ss .usermodel .DateUtil ;
10+ import org .apache .poi .ss .usermodel .Row ;
11+ import org .apache .poi .ss .usermodel .Sheet ;
12+ import org .apache .poi .ss .usermodel .Workbook ;
13+ import org .apache .poi .xssf .usermodel .XSSFWorkbook ;
14+
15+ public class ExcelUtility {
16+ private static final String ENDLINE = System .getProperty ("line.separator" );
17+
18+ public static String readExcel (String filePath ) throws IOException {
19+ File file = new File (filePath );
20+ FileInputStream inputStream = null ;
21+ StringBuilder toReturn = new StringBuilder ();
22+ try {
23+ inputStream = new FileInputStream (file );
24+ Workbook baeuldungWorkBook = new XSSFWorkbook (inputStream );
25+ for (Sheet sheet : baeuldungWorkBook ) {
26+ toReturn .append ("--------------------------------------------------------------------" ).append (ENDLINE );
27+ toReturn .append ("Worksheet :" ).append (sheet .getSheetName ()).append (ENDLINE );
28+ toReturn .append ("--------------------------------------------------------------------" ).append (ENDLINE );
29+ int firstRow = sheet .getFirstRowNum ();
30+ int lastRow = sheet .getLastRowNum ();
31+ for (int index = firstRow + 1 ; index <= lastRow ; index ++) {
32+ Row row = sheet .getRow (index );
33+ toReturn .append ("|| " );
34+ for (int cellIndex = row .getFirstCellNum (); cellIndex < row .getLastCellNum (); cellIndex ++) {
35+ Cell cell = row .getCell (cellIndex , Row .MissingCellPolicy .CREATE_NULL_AS_BLANK );
36+ printCellValue (cell , toReturn );
37+ }
38+ toReturn .append (" ||" ).append (ENDLINE );
39+ }
40+ }
41+ inputStream .close ();
42+
43+ } catch (IOException e ) {
44+ throw e ;
45+ }
46+ return toReturn .toString ();
47+ }
48+
49+ public static void printCellValue (Cell cell , StringBuilder toReturn ) {
50+ CellType cellType = cell .getCellType ().equals (CellType .FORMULA ) ? cell .getCachedFormulaResultType ()
51+ : cell .getCellType ();
52+ if (cellType .equals (CellType .STRING )) {
53+ toReturn .append (cell .getStringCellValue ()).append (" | " );
54+ }
55+ if (cellType .equals (CellType .NUMERIC )) {
56+ if (DateUtil .isCellDateFormatted (cell )) {
57+ toReturn .append (cell .getDateCellValue ()).append (" | " );
58+ } else {
59+ toReturn .append (cell .getNumericCellValue ()).append (" | " );
60+ }
61+ }
62+ if (cellType .equals (CellType .BOOLEAN )) {
63+ toReturn .append (cell .getBooleanCellValue ()).append (" | " );
64+ }
65+ }
66+ }
0 commit comments