Skip to content

Commit a5f3271

Browse files
committed
Methods have been added to be able to write a CSV file or a list of objects to an Excel file that already exists
1 parent 3fd86f9 commit a5f3271

File tree

5 files changed

+128
-19
lines changed

5 files changed

+128
-19
lines changed

src/main/java/samples/convertCsvFileToExcelFile/Main.java

+11
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
11
package samples.convertCsvFileToExcelFile;
22

33
import enums.Extension;
4+
import org.apache.poi.ss.usermodel.Workbook;
45
import tools.Converter;
6+
import tools.WorkbookUtility;
57

68
import java.io.File;
9+
import java.io.FileOutputStream;
710

811
public class Main {
912

1013
public static void main(String[] args) {
1114

1215
File csvFile = new File("./src/main/resources/employee.csv");
16+
File csvFile2 = new File("./src/main/resources/employee_2.csv");
1317

1418
try {
1519
System.out.println("Start the conversion...");
1620
File excelFile = Converter.csvToExcel(csvFile, "./src/main/resources/", "employee_2", Extension.XLSX);
21+
System.out.println("First conversion completed...");
22+
23+
Workbook workbook = WorkbookUtility.open(excelFile);
24+
Converter.csvToExistingExcel(workbook, csvFile2);
25+
FileOutputStream fileOutputStream = new FileOutputStream(excelFile);
26+
workbook.write(fileOutputStream);
27+
WorkbookUtility.close(workbook, fileOutputStream);
1728
System.out.println("The file is ready. Path: " + excelFile.getAbsolutePath());
1829
} catch (Exception e) {
1930
System.err.println("There was an error. Check the console");

src/main/java/samples/convertObjectsToExcelFileSample/Main.java

+15
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
package samples.convertObjectsToExcelFileSample;
22

33
import enums.Extension;
4+
import org.apache.poi.ss.usermodel.Workbook;
45
import tools.Converter;
6+
import tools.WorkbookUtility;
57

68
import java.io.File;
9+
import java.io.FileOutputStream;
710
import java.time.LocalDate;
811
import java.time.LocalDateTime;
912
import java.util.ArrayList;
1013
import java.util.Date;
14+
import java.util.LinkedList;
1115
import java.util.List;
1216

1317
public class Main {
@@ -18,9 +22,20 @@ public static void main(String[] args) {
1822
employees.add(new Employee("Rossi", "Mario", 25, LocalDate.of(1987, 5, 22), new Date(), 28000.00, LocalDateTime.now(), true));
1923
employees.add(new Employee("Verdi", "Giuseppe", 22, LocalDate.of(1991, 2, 23), new Date(), 23670.89, LocalDateTime.now(), false));
2024

25+
List<Office> offices = new LinkedList<>();
26+
offices.add(new Office("Nocera Inferiore", "Salerno", 40));
27+
offices.add(new Office("Pero", "Milano", 73));
28+
2129
try {
2230
System.out.println("Start the conversion...");
2331
File report = Converter.objectsToExcel(employees, Employee.class, "./src/main/resources/", "employee", Extension.XLSX, true);
32+
System.out.println("First conversion completed...");
33+
34+
Workbook workbook = WorkbookUtility.open(report);
35+
Converter.objectsToExistingExcel(workbook, offices, Office.class, true);
36+
FileOutputStream fileOutputStream = new FileOutputStream(report);
37+
workbook.write(fileOutputStream);
38+
WorkbookUtility.close(workbook, fileOutputStream);
2439
System.out.println("The file is ready. Path: " + report.getAbsolutePath());
2540
} catch (Exception e) {
2641
System.err.println("There was an error. Check the console");
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package samples.convertObjectsToExcelFileSample;
2+
3+
import annotations.ExcelBodyStyle;
4+
import annotations.ExcelField;
5+
import annotations.ExcelHeaderStyle;
6+
import lombok.AllArgsConstructor;
7+
import lombok.NoArgsConstructor;
8+
import lombok.ToString;
9+
10+
@AllArgsConstructor
11+
@NoArgsConstructor
12+
@ToString
13+
@ExcelHeaderStyle(autoSize = true)
14+
@ExcelBodyStyle
15+
public class Office {
16+
@ExcelField(name = "CITY")
17+
private String city;
18+
@ExcelField(name = "PROVINCE")
19+
private String province;
20+
@ExcelField(name = "NUMBER OF STATIONS")
21+
private Integer numStations;
22+
}

src/main/java/tools/Converter.java

+80-18
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,42 @@ public static File objectsToExcel(List<?> objects, Class<?> clazz, String path,
252252

253253
/* Create workbook and sheet */
254254
Workbook workbook = WorkbookUtility.create(extension);
255+
objectsToExistingExcel(workbook, objects, clazz, writeHeader);
256+
257+
/* Write file */
258+
FileOutputStream fileOutputStream = new FileOutputStream(file);
259+
workbook.write(fileOutputStream);
260+
261+
/* Close file */
262+
WorkbookUtility.close(workbook, fileOutputStream);
263+
264+
return file;
265+
}
266+
267+
/**
268+
* This method allows you to convert objects into a Sheet of a Workbook that already exists.<p>
269+
* Note: This method does not call the "write" method of the workbook.<p>
270+
* By default, the header is added if not specified
271+
* @param workbook The {@code Workbook} to update
272+
* @param objects The list of objects that will be converted into an Excel file
273+
* @param clazz The class of the list elements
274+
* @throws IllegalAccessException If a field or fields of the {@code clazz} could not be accessed
275+
*/
276+
public static void objectsToExistingExcel(Workbook workbook, List<?> objects, Class<?> clazz) throws IllegalAccessException {
277+
objectsToExistingExcel(workbook, objects, clazz, true);
278+
}
279+
280+
/**
281+
* This method allows you to convert objects into a Sheet of a Workbook that already exists.<p>
282+
* Note: This method does not call the "write" method of the workbook.
283+
* @param workbook The {@code Workbook} to update
284+
* @param objects The list of objects that will be converted into an Excel file
285+
* @param clazz The class of the list elements
286+
* @param writeHeader If {@code true} it will write the header to the first line
287+
* @throws IllegalAccessException If a field or fields of the {@code clazz} could not be accessed
288+
*/
289+
public static void objectsToExistingExcel(Workbook workbook, List<?> objects, Class<?> clazz, Boolean writeHeader) throws IllegalAccessException {
290+
/* Create sheet */
255291
Sheet sheet = SheetUtility.create(workbook, clazz.getSimpleName());
256292

257293
Field[] fields = clazz.getDeclaredFields();
@@ -269,15 +305,6 @@ public static File objectsToExcel(List<?> objects, Class<?> clazz, String path,
269305
CellStyle bodyCellStyle = createBodyStyle(workbook, clazz);
270306
writeExcelBody(workbook, sheet, fields, object, cRow++, bodyCellStyle, clazz);
271307
}
272-
273-
/* Write file */
274-
FileOutputStream fileOutputStream = new FileOutputStream(file);
275-
workbook.write(fileOutputStream);
276-
277-
/* Close file */
278-
WorkbookUtility.close(workbook, fileOutputStream);
279-
280-
return file;
281308
}
282309

283310
/**
@@ -518,6 +545,50 @@ public static File csvToExcel(File fileInput, String path, String filename, Exte
518545

519546
/* Create workbook and sheet */
520547
Workbook workbook = WorkbookUtility.create(extension);
548+
csvToExistingExcel(workbook, csvReader);
549+
550+
/* Write file */
551+
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
552+
workbook.write(fileOutputStream);
553+
554+
/* Close file */
555+
WorkbookUtility.close(workbook, fileOutputStream, csvReader);
556+
557+
return outputFile;
558+
}
559+
560+
/**
561+
* Convert the CSV file into a new sheet of an existing Workbook.<p>
562+
* Note: This method does not call the "write" method of the workbook.
563+
* @param workbook The {@code Workbook} to update
564+
* @param fileInput The input CSV file that will be converted into an Excel file
565+
* @throws IOException If an I/O error has occurred
566+
* @throws CsvValidationException If the CSV file has invalid formatting
567+
* @throws ExtensionNotValidException If the input file extension does not belong to a CSV file
568+
*/
569+
public static void csvToExistingExcel(Workbook workbook, File fileInput) throws IOException, CsvValidationException, ExtensionNotValidException {
570+
/* Check exension */
571+
String csvExt = FilenameUtils.getExtension(fileInput.getName());
572+
isValidCsvExtension(csvExt);
573+
574+
/* Open CSV file */
575+
FileReader fileReader = new FileReader(fileInput);
576+
CSVReader csvReader = new CSVReader(fileReader);
577+
csvToExistingExcel(workbook, csvReader);
578+
579+
/* Close CSV reader */
580+
csvReader.close();
581+
}
582+
583+
/**
584+
* Writes the data present in the CSVReader to a new sheet of an existing Workbook.<p>
585+
* Note: This method does not call the "write" method of the workbook.
586+
* @param workbook The {@code Workbook} to update
587+
* @param csvReader The {@code CSVReader} of the CSV input file
588+
* @throws CsvValidationException If the CSV file has invalid formatting
589+
* @throws IOException If an I/O error has occurred
590+
*/
591+
public static void csvToExistingExcel(Workbook workbook, CSVReader csvReader) throws CsvValidationException, IOException {
521592
Sheet sheet = SheetUtility.create(workbook);
522593

523594
/* Read CSV file */
@@ -532,15 +603,6 @@ public static File csvToExcel(File fileInput, String path, String filename, Exte
532603
}
533604
cRow++;
534605
}
535-
536-
/* Write file */
537-
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
538-
workbook.write(fileOutputStream);
539-
540-
/* Close file */
541-
WorkbookUtility.close(workbook, fileOutputStream, csvReader);
542-
543-
return outputFile;
544606
}
545607

546608
private static void isValidCsvExtension(String extension) throws ExtensionNotValidException {

src/main/java/tools/ExcelUtility.java

-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import org.apache.poi.ss.usermodel.Workbook;
1212

1313
import java.io.File;
14-
import java.io.FileInputStream;
1514
import java.io.IOException;
1615
import java.util.LinkedList;
1716
import java.util.List;

0 commit comments

Comments
 (0)