├── .gitignore
├── Readme.md
├── poi-generated-file.xlsx
├── pom.xml
├── sample-xls-file.xls
├── sample-xlsx-file.xlsx
└── src
└── main
└── java
├── ExcelReader.java
└── ExcelWriter.java
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | .idea
3 | *.class
4 | target
5 | *.iml
6 |
--------------------------------------------------------------------------------
/Readme.md:
--------------------------------------------------------------------------------
1 | ## Learn how to Read and Write Excel files in Java using Apache POI
2 |
3 | [How to Read Excel files in Java using Apache POI](https://www.callicoder.com/java-read-excel-file-apache-poi/)
4 |
5 | [How to Write to an Excel file in Java using Apache POI](https://www.callicoder.com/java-write-excel-file-apache-poi/)
--------------------------------------------------------------------------------
/poi-generated-file.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/callicoder/java-read-write-excel-file-using-apache-poi/c68f5375bb860a02c9b8368c134fd89c56db30f9/poi-generated-file.xlsx
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.callicoder
8 | excel-utils
9 | 1.0-SNAPSHOT
10 |
11 |
12 | UTF-8
13 | UTF-8
14 | 1.8
15 |
16 |
17 |
18 |
19 |
20 | org.apache.poi
21 | poi
22 | 3.17
23 |
24 |
25 |
26 |
27 | org.apache.poi
28 | poi-ooxml
29 | 3.17
30 |
31 |
32 |
33 |
34 |
35 |
36 | org.apache.maven.plugins
37 | maven-compiler-plugin
38 | 3.7.0
39 |
40 | ${java.version}
41 | ${java.version}
42 |
43 |
44 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/sample-xls-file.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/callicoder/java-read-write-excel-file-using-apache-poi/c68f5375bb860a02c9b8368c134fd89c56db30f9/sample-xls-file.xls
--------------------------------------------------------------------------------
/sample-xlsx-file.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/callicoder/java-read-write-excel-file-using-apache-poi/c68f5375bb860a02c9b8368c134fd89c56db30f9/sample-xlsx-file.xlsx
--------------------------------------------------------------------------------
/src/main/java/ExcelReader.java:
--------------------------------------------------------------------------------
1 | import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
2 | import org.apache.poi.ss.usermodel.*;
3 |
4 | import java.io.File;
5 | import java.io.IOException;
6 | import java.util.Iterator;
7 |
8 | /**
9 | * Created by rajeevkumarsingh on 18/12/17.
10 | */
11 |
12 | public class ExcelReader {
13 | public static final String SAMPLE_XLS_FILE_PATH = "./sample-xls-file.xls";
14 | public static final String SAMPLE_XLSX_FILE_PATH = "./sample-xlsx-file.xlsx";
15 |
16 | public static void main(String[] args) throws IOException, InvalidFormatException {
17 |
18 | // Creating a Workbook from an Excel file (.xls or .xlsx)
19 | Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
20 |
21 | // Retrieving the number of sheets in the Workbook
22 | System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
23 |
24 | /*
25 | =============================================================
26 | Iterating over all the sheets in the workbook (Multiple ways)
27 | =============================================================
28 | */
29 |
30 | // 1. You can obtain a sheetIterator and iterate over it
31 | Iterator sheetIterator = workbook.sheetIterator();
32 | System.out.println("Retrieving Sheets using Iterator");
33 | while (sheetIterator.hasNext()) {
34 | Sheet sheet = sheetIterator.next();
35 | System.out.println("=> " + sheet.getSheetName());
36 | }
37 |
38 | // 2. Or you can use a for-each loop
39 | System.out.println("Retrieving Sheets using for-each loop");
40 | for(Sheet sheet: workbook) {
41 | System.out.println("=> " + sheet.getSheetName());
42 | }
43 |
44 | // 3. Or you can use a Java 8 forEach wih lambda
45 | System.out.println("Retrieving Sheets using Java 8 forEach with lambda");
46 | workbook.forEach(sheet -> {
47 | System.out.println("=> " + sheet.getSheetName());
48 | });
49 |
50 | /*
51 | ==================================================================
52 | Iterating over all the rows and columns in a Sheet (Multiple ways)
53 | ==================================================================
54 | */
55 |
56 | // Getting the Sheet at index zero
57 | Sheet sheet = workbook.getSheetAt(0);
58 |
59 | // Create a DataFormatter to format and get each cell's value as String
60 | DataFormatter dataFormatter = new DataFormatter();
61 |
62 | // 1. You can obtain a rowIterator and columnIterator and iterate over them
63 | System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
64 | Iterator rowIterator = sheet.rowIterator();
65 | while (rowIterator.hasNext()) {
66 | Row row = rowIterator.next();
67 |
68 | // Now let's iterate over the columns of the current row
69 | Iterator cellIterator = row.cellIterator();
70 |
71 | while (cellIterator.hasNext()) {
72 | Cell cell = cellIterator.next();
73 | String cellValue = dataFormatter.formatCellValue(cell);
74 | System.out.print(cellValue + "\t");
75 | }
76 | System.out.println();
77 | }
78 |
79 | // 2. Or you can use a for-each loop to iterate over the rows and columns
80 | System.out.println("\n\nIterating over Rows and Columns using for-each loop\n");
81 | for (Row row: sheet) {
82 | for(Cell cell: row) {
83 | String cellValue = dataFormatter.formatCellValue(cell);
84 | System.out.print(cellValue + "\t");
85 | }
86 | System.out.println();
87 | }
88 |
89 | // 3. Or you can use Java 8 forEach loop with lambda
90 | System.out.println("\n\nIterating over Rows and Columns using Java 8 forEach with lambda\n");
91 | sheet.forEach(row -> {
92 | row.forEach(cell -> {
93 | printCellValue(cell);
94 | });
95 | System.out.println();
96 | });
97 |
98 | // Closing the workbook
99 | workbook.close();
100 | }
101 |
102 | private static void printCellValue(Cell cell) {
103 | switch (cell.getCellTypeEnum()) {
104 | case BOOLEAN:
105 | System.out.print(cell.getBooleanCellValue());
106 | break;
107 | case STRING:
108 | System.out.print(cell.getRichStringCellValue().getString());
109 | break;
110 | case NUMERIC:
111 | if (DateUtil.isCellDateFormatted(cell)) {
112 | System.out.print(cell.getDateCellValue());
113 | } else {
114 | System.out.print(cell.getNumericCellValue());
115 | }
116 | break;
117 | case FORMULA:
118 | System.out.print(cell.getCellFormula());
119 | break;
120 | case BLANK:
121 | System.out.print("");
122 | break;
123 | default:
124 | System.out.print("");
125 | }
126 |
127 | System.out.print("\t");
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/src/main/java/ExcelWriter.java:
--------------------------------------------------------------------------------
1 | import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
2 | import org.apache.poi.ss.usermodel.*;
3 | import org.apache.poi.xssf.usermodel.XSSFWorkbook;
4 |
5 | import java.io.File;
6 | import java.io.FileOutputStream;
7 | import java.io.IOException;
8 | import java.util.ArrayList;
9 | import java.util.Calendar;
10 | import java.util.Date;
11 | import java.util.List;
12 |
13 | /**
14 | * Created by rajeevkumarsingh on 22/12/17.
15 | */
16 |
17 | public class ExcelWriter {
18 |
19 | private static String[] columns = {"Name", "Email", "Date Of Birth", "Salary"};
20 |
21 | private static List employees = new ArrayList<>();
22 |
23 | static {
24 | Calendar dateOfBirth = Calendar.getInstance();
25 | dateOfBirth.set(1992, 7, 21);
26 | employees.add(new Employee("Rajeev Singh", "rajeev@example.com",
27 | dateOfBirth.getTime(), 1200000.0));
28 |
29 | dateOfBirth.set(1965, 10, 15);
30 | employees.add(new Employee("Thomas cook", "thomas@example.com",
31 | dateOfBirth.getTime(), 1500000.0));
32 |
33 | dateOfBirth.set(1987, 4, 18);
34 | employees.add(new Employee("Steve Maiden", "steve@example.com",
35 | dateOfBirth.getTime(), 1800000.0));
36 | }
37 |
38 | public static void main(String[] args) throws IOException, InvalidFormatException {
39 |
40 | // Create a Workbook
41 | Workbook workbook = new XSSFWorkbook(); // new HSSFWorkbook() for generating `.xls` file
42 |
43 | /* CreationHelper helps us create instances for various things like DataFormat,
44 | Hyperlink, RichTextString etc in a format (HSSF, XSSF) independent way */
45 | CreationHelper createHelper = workbook.getCreationHelper();
46 |
47 | // Create a Sheet
48 | Sheet sheet = workbook.createSheet("Employee");
49 |
50 | // Create a Font for styling header cells
51 | Font headerFont = workbook.createFont();
52 | headerFont.setBold(true);
53 | headerFont.setFontHeightInPoints((short) 14);
54 | headerFont.setColor(IndexedColors.RED.getIndex());
55 |
56 | // Create a CellStyle with the font
57 | CellStyle headerCellStyle = workbook.createCellStyle();
58 | headerCellStyle.setFont(headerFont);
59 |
60 | // Create a Row
61 | Row headerRow = sheet.createRow(0);
62 |
63 | // Creating cells
64 | for(int i = 0; i < columns.length; i++) {
65 | Cell cell = headerRow.createCell(i);
66 | cell.setCellValue(columns[i]);
67 | cell.setCellStyle(headerCellStyle);
68 | }
69 |
70 | // Cell Style for formatting Date
71 | CellStyle dateCellStyle = workbook.createCellStyle();
72 | dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
73 |
74 | // Create Other rows and cells with employees data
75 | int rowNum = 1;
76 | for(Employee employee: employees) {
77 | Row row = sheet.createRow(rowNum++);
78 |
79 | row.createCell(0)
80 | .setCellValue(employee.getName());
81 |
82 | row.createCell(1)
83 | .setCellValue(employee.getEmail());
84 |
85 | Cell dateOfBirthCell = row.createCell(2);
86 | dateOfBirthCell.setCellValue(employee.getDateOfBirth());
87 | dateOfBirthCell.setCellStyle(dateCellStyle);
88 |
89 | row.createCell(3)
90 | .setCellValue(employee.getSalary());
91 | }
92 |
93 | // Resize all columns to fit the content size
94 | for(int i = 0; i < columns.length; i++) {
95 | sheet.autoSizeColumn(i);
96 | }
97 |
98 | // Write the output to a file
99 | FileOutputStream fileOut = new FileOutputStream("poi-generated-file.xlsx");
100 | workbook.write(fileOut);
101 | fileOut.close();
102 |
103 | workbook.close();
104 | }
105 |
106 |
107 | // Example to modify an existing excel file
108 | private static void modifyExistingWorkbook() throws InvalidFormatException, IOException {
109 | // Obtain a workbook from the excel file
110 | Workbook workbook = WorkbookFactory.create(new File("existing-spreadsheet.xlsx"));
111 |
112 | // Get Sheet at index 0
113 | Sheet sheet = workbook.getSheetAt(0);
114 |
115 | // Get Row at index 1
116 | Row row = sheet.getRow(1);
117 |
118 | // Get the Cell at index 2 from the above row
119 | Cell cell = row.getCell(2);
120 |
121 | // Create the cell if it doesn't exist
122 | if (cell == null)
123 | cell = row.createCell(2);
124 |
125 | // Update the cell's value
126 | cell.setCellType(CellType.STRING);
127 | cell.setCellValue("Updated Value");
128 |
129 | // Write the output to a file
130 | FileOutputStream fileOut = new FileOutputStream("existing-spreadsheet.xlsx");
131 | workbook.write(fileOut);
132 | fileOut.close();
133 |
134 | // Closing the workbook
135 | workbook.close();
136 | }
137 | }
138 |
139 |
140 | class Employee {
141 | private String name;
142 |
143 | private String email;
144 |
145 | private Date dateOfBirth;
146 |
147 | private double salary;
148 |
149 | public Employee(String name, String email, Date dateOfBirth, double salary) {
150 | this.name = name;
151 | this.email = email;
152 | this.dateOfBirth = dateOfBirth;
153 | this.salary = salary;
154 | }
155 |
156 | public String getName() {
157 | return name;
158 | }
159 |
160 | public void setName(String name) {
161 | this.name = name;
162 | }
163 |
164 | public String getEmail() {
165 | return email;
166 | }
167 |
168 | public void setEmail(String email) {
169 | this.email = email;
170 | }
171 |
172 | public Date getDateOfBirth() {
173 | return dateOfBirth;
174 | }
175 |
176 | public void setDateOfBirth(Date dateOfBirth) {
177 | this.dateOfBirth = dateOfBirth;
178 | }
179 |
180 | public double getSalary() {
181 | return salary;
182 | }
183 |
184 | public void setSalary(double salary) {
185 | this.salary = salary;
186 | }
187 | }
188 |
--------------------------------------------------------------------------------
|