Skip to content

Commit 1c9f69d

Browse files
author
Rajeev Kumar Singh
committed
initial commit
0 parents  commit 1c9f69d

7 files changed

+324
-0
lines changed

Diff for: .gitignore

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
.DS_Store
2+
.idea
3+
*.class
4+
target
5+
*.iml

Diff for: poi-generated-file.xlsx

3.59 KB
Binary file not shown.

Diff for: pom.xml

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.callicoder</groupId>
8+
<artifactId>excel-utils</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
12+
<dependencies>
13+
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
14+
<dependency>
15+
<groupId>org.apache.poi</groupId>
16+
<artifactId>poi</artifactId>
17+
<version>3.17</version>
18+
</dependency>
19+
20+
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
21+
<dependency>
22+
<groupId>org.apache.poi</groupId>
23+
<artifactId>poi-ooxml</artifactId>
24+
<version>3.17</version>
25+
</dependency>
26+
</dependencies>
27+
28+
<build>
29+
<plugins>
30+
<plugin>
31+
<groupId>org.apache.maven.plugins</groupId>
32+
<artifactId>maven-compiler-plugin</artifactId>
33+
<configuration>
34+
<source>1.8</source>
35+
<target>1.8</target>
36+
</configuration>
37+
</plugin>
38+
</plugins>
39+
</build>
40+
</project>

Diff for: sample-xls-file.xls

19 KB
Binary file not shown.

Diff for: sample-xlsx-file.xlsx

5.17 KB
Binary file not shown.

Diff for: src/main/java/ExcelReader.java

+131
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
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<Sheet> 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+
/*
53+
==================================================================
54+
Iterating over all the rows and columns in a Sheet (Multiple ways)
55+
==================================================================
56+
*/
57+
58+
// Getting the Sheet at index zero
59+
Sheet sheet = workbook.getSheetAt(0);
60+
61+
// Create a DataFormatter to format and get each cell's value as String
62+
DataFormatter dataFormatter = new DataFormatter();
63+
64+
// 1. You can obtain a rowIterator and columnIterator and iterate over them
65+
System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
66+
Iterator<Row> rowIterator = sheet.rowIterator();
67+
while (rowIterator.hasNext()) {
68+
Row row = rowIterator.next();
69+
70+
// Now let's iterate over the columns of the current row
71+
Iterator<Cell> cellIterator = row.cellIterator();
72+
73+
while (cellIterator.hasNext()) {
74+
Cell cell = cellIterator.next();
75+
String cellValue = dataFormatter.formatCellValue(cell);
76+
System.out.print(cellValue + "\t");
77+
}
78+
System.out.println();
79+
}
80+
81+
// 2. Or you can use a for-each loop to iterate over the rows and columns
82+
System.out.println("\n\nIterating over Rows and Columns using for-each loop\n");
83+
for (Row row: sheet) {
84+
for(Cell cell: row) {
85+
String cellValue = dataFormatter.formatCellValue(cell);
86+
System.out.print(cellValue + "\t");
87+
}
88+
System.out.println();
89+
}
90+
91+
// 3. Or you can use Java 8 forEach loop with lambda
92+
System.out.println("\n\nIterating over Rows and Columns using Java 8 forEach with lambda\n");
93+
sheet.forEach(row -> {
94+
row.forEach(cell -> {
95+
printCellValue(cell);
96+
});
97+
System.out.println();
98+
});
99+
100+
// Closing the workbook
101+
workbook.close();
102+
}
103+
104+
private static void printCellValue(Cell cell) {
105+
switch (cell.getCellTypeEnum()) {
106+
case BOOLEAN:
107+
System.out.print(cell.getBooleanCellValue());
108+
break;
109+
case STRING:
110+
System.out.print(cell.getRichStringCellValue().getString());
111+
break;
112+
case NUMERIC:
113+
if (DateUtil.isCellDateFormatted(cell)) {
114+
System.out.print(cell.getDateCellValue());
115+
} else {
116+
System.out.print(cell.getNumericCellValue());
117+
}
118+
break;
119+
case FORMULA:
120+
System.out.print(cell.getCellFormula());
121+
break;
122+
case BLANK:
123+
System.out.print("");
124+
break;
125+
default:
126+
System.out.print("");
127+
}
128+
129+
System.out.print("\t");
130+
}
131+
}

Diff for: src/main/java/ExcelWriter.java

+148
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
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.FileOutputStream;
6+
import java.io.IOException;
7+
import java.util.ArrayList;
8+
import java.util.Calendar;
9+
import java.util.Date;
10+
import java.util.List;
11+
12+
/**
13+
* Created by rajeevkumarsingh on 22/12/17.
14+
*/
15+
16+
public class ExcelWriter {
17+
18+
private static String[] columns = {"Name", "Email", "Date Of Birth", "Salary"};
19+
20+
private static List<Employee> employees = new ArrayList<>();
21+
22+
static {
23+
Calendar dateOfBirth = Calendar.getInstance();
24+
dateOfBirth.set(1992, 7, 21);
25+
employees.add(new Employee("Rajeev Singh", "[email protected]",
26+
dateOfBirth.getTime(), 1200000.0));
27+
28+
dateOfBirth.set(1965, 10, 15);
29+
employees.add(new Employee("Thomas cook", "[email protected]",
30+
dateOfBirth.getTime(), 1500000.0));
31+
32+
dateOfBirth.set(1987, 4, 18);
33+
employees.add(new Employee("Steve Maiden", "[email protected]",
34+
dateOfBirth.getTime(), 1800000.0));
35+
}
36+
37+
public static void main(String[] args) throws IOException, InvalidFormatException {
38+
39+
// Create a Workbook
40+
Workbook workbook = new XSSFWorkbook();
41+
CreationHelper createHelper = workbook.getCreationHelper();
42+
43+
// Create a Sheet
44+
Sheet sheet = workbook.createSheet("Employee");
45+
46+
// Create a Font for styling header cells
47+
Font headerFont = workbook.createFont();
48+
headerFont.setBold(true);
49+
headerFont.setFontHeight((short) 16);
50+
headerFont.setColor(IndexedColors.RED.getIndex());
51+
52+
// Create a CellStyle with the font
53+
CellStyle headerCellStyle = workbook.createCellStyle();
54+
headerCellStyle.setFont(headerFont);
55+
56+
// Create a Row
57+
Row headerRow = sheet.createRow(0);
58+
59+
// Creating cells
60+
for(int i = 0; i < columns.length; i++) {
61+
Cell cell = headerRow.createCell(i);
62+
cell.setCellValue(columns[i]);
63+
cell.setCellStyle(headerCellStyle);
64+
}
65+
66+
// Cell Style for formatting Date
67+
CellStyle dateCellStyle = workbook.createCellStyle();
68+
dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
69+
70+
// Create Other rows and cells with employees data
71+
int rowNum = 1;
72+
for(Employee employee: employees) {
73+
Row row = sheet.createRow(rowNum++);
74+
75+
row.createCell(0)
76+
.setCellValue(employee.getName());
77+
78+
row.createCell(1)
79+
.setCellValue(employee.getEmail());
80+
81+
Cell dobCell = row.createCell(2);
82+
dobCell.setCellValue(employee.getDateOfBirth());
83+
dobCell.setCellStyle(dateCellStyle);
84+
85+
row.createCell(3)
86+
.setCellValue(employee.getSalary());
87+
}
88+
89+
for(int i = 0; i < columns.length; i++) {
90+
sheet.autoSizeColumn(i);
91+
}
92+
93+
// Write the output to a file
94+
FileOutputStream fileOut = new FileOutputStream("poi-generated-file.xlsx");
95+
workbook.write(fileOut);
96+
fileOut.close();
97+
}
98+
}
99+
100+
101+
class Employee {
102+
private String name;
103+
104+
private String email;
105+
106+
private Date dateOfBirth;
107+
108+
private double salary;
109+
110+
public Employee(String name, String email, Date dateOfBirth, double salary) {
111+
this.name = name;
112+
this.email = email;
113+
this.dateOfBirth = dateOfBirth;
114+
this.salary = salary;
115+
}
116+
117+
public String getName() {
118+
return name;
119+
}
120+
121+
public void setName(String name) {
122+
this.name = name;
123+
}
124+
125+
public String getEmail() {
126+
return email;
127+
}
128+
129+
public void setEmail(String email) {
130+
this.email = email;
131+
}
132+
133+
public Date getDateOfBirth() {
134+
return dateOfBirth;
135+
}
136+
137+
public void setDateOfBirth(Date dateOfBirth) {
138+
this.dateOfBirth = dateOfBirth;
139+
}
140+
141+
public double getSalary() {
142+
return salary;
143+
}
144+
145+
public void setSalary(double salary) {
146+
this.salary = salary;
147+
}
148+
}

0 commit comments

Comments
 (0)