Skip to content

Commit

Permalink
Methods have been added to be able to write a CSV file or a list of o…
Browse files Browse the repository at this point in the history
…bjects to an Excel file that already exists
  • Loading branch information
MBenincasa committed Jan 29, 2023
1 parent 3fd86f9 commit a5f3271
Show file tree
Hide file tree
Showing 5 changed files with 128 additions and 19 deletions.
11 changes: 11 additions & 0 deletions src/main/java/samples/convertCsvFileToExcelFile/Main.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
package samples.convertCsvFileToExcelFile;

import enums.Extension;
import org.apache.poi.ss.usermodel.Workbook;
import tools.Converter;
import tools.WorkbookUtility;

import java.io.File;
import java.io.FileOutputStream;

public class Main {

public static void main(String[] args) {

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

try {
System.out.println("Start the conversion...");
File excelFile = Converter.csvToExcel(csvFile, "./src/main/resources/", "employee_2", Extension.XLSX);
System.out.println("First conversion completed...");

Workbook workbook = WorkbookUtility.open(excelFile);
Converter.csvToExistingExcel(workbook, csvFile2);
FileOutputStream fileOutputStream = new FileOutputStream(excelFile);
workbook.write(fileOutputStream);
WorkbookUtility.close(workbook, fileOutputStream);
System.out.println("The file is ready. Path: " + excelFile.getAbsolutePath());
} catch (Exception e) {
System.err.println("There was an error. Check the console");
Expand Down
15 changes: 15 additions & 0 deletions src/main/java/samples/convertObjectsToExcelFileSample/Main.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package samples.convertObjectsToExcelFileSample;

import enums.Extension;
import org.apache.poi.ss.usermodel.Workbook;
import tools.Converter;
import tools.WorkbookUtility;

import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

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

List<Office> offices = new LinkedList<>();
offices.add(new Office("Nocera Inferiore", "Salerno", 40));
offices.add(new Office("Pero", "Milano", 73));

try {
System.out.println("Start the conversion...");
File report = Converter.objectsToExcel(employees, Employee.class, "./src/main/resources/", "employee", Extension.XLSX, true);
System.out.println("First conversion completed...");

Workbook workbook = WorkbookUtility.open(report);
Converter.objectsToExistingExcel(workbook, offices, Office.class, true);
FileOutputStream fileOutputStream = new FileOutputStream(report);
workbook.write(fileOutputStream);
WorkbookUtility.close(workbook, fileOutputStream);
System.out.println("The file is ready. Path: " + report.getAbsolutePath());
} catch (Exception e) {
System.err.println("There was an error. Check the console");
Expand Down
22 changes: 22 additions & 0 deletions src/main/java/samples/convertObjectsToExcelFileSample/Office.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package samples.convertObjectsToExcelFileSample;

import annotations.ExcelBodyStyle;
import annotations.ExcelField;
import annotations.ExcelHeaderStyle;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.ToString;

@AllArgsConstructor
@NoArgsConstructor
@ToString
@ExcelHeaderStyle(autoSize = true)
@ExcelBodyStyle
public class Office {
@ExcelField(name = "CITY")
private String city;
@ExcelField(name = "PROVINCE")
private String province;
@ExcelField(name = "NUMBER OF STATIONS")
private Integer numStations;
}
98 changes: 80 additions & 18 deletions src/main/java/tools/Converter.java
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,42 @@ public static File objectsToExcel(List<?> objects, Class<?> clazz, String path,

/* Create workbook and sheet */
Workbook workbook = WorkbookUtility.create(extension);
objectsToExistingExcel(workbook, objects, clazz, writeHeader);

/* Write file */
FileOutputStream fileOutputStream = new FileOutputStream(file);
workbook.write(fileOutputStream);

/* Close file */
WorkbookUtility.close(workbook, fileOutputStream);

return file;
}

/**
* This method allows you to convert objects into a Sheet of a Workbook that already exists.<p>
* Note: This method does not call the "write" method of the workbook.<p>
* By default, the header is added if not specified
* @param workbook The {@code Workbook} to update
* @param objects The list of objects that will be converted into an Excel file
* @param clazz The class of the list elements
* @throws IllegalAccessException If a field or fields of the {@code clazz} could not be accessed
*/
public static void objectsToExistingExcel(Workbook workbook, List<?> objects, Class<?> clazz) throws IllegalAccessException {
objectsToExistingExcel(workbook, objects, clazz, true);
}

/**
* This method allows you to convert objects into a Sheet of a Workbook that already exists.<p>
* Note: This method does not call the "write" method of the workbook.
* @param workbook The {@code Workbook} to update
* @param objects The list of objects that will be converted into an Excel file
* @param clazz The class of the list elements
* @param writeHeader If {@code true} it will write the header to the first line
* @throws IllegalAccessException If a field or fields of the {@code clazz} could not be accessed
*/
public static void objectsToExistingExcel(Workbook workbook, List<?> objects, Class<?> clazz, Boolean writeHeader) throws IllegalAccessException {
/* Create sheet */
Sheet sheet = SheetUtility.create(workbook, clazz.getSimpleName());

Field[] fields = clazz.getDeclaredFields();
Expand All @@ -269,15 +305,6 @@ public static File objectsToExcel(List<?> objects, Class<?> clazz, String path,
CellStyle bodyCellStyle = createBodyStyle(workbook, clazz);
writeExcelBody(workbook, sheet, fields, object, cRow++, bodyCellStyle, clazz);
}

/* Write file */
FileOutputStream fileOutputStream = new FileOutputStream(file);
workbook.write(fileOutputStream);

/* Close file */
WorkbookUtility.close(workbook, fileOutputStream);

return file;
}

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

/* Create workbook and sheet */
Workbook workbook = WorkbookUtility.create(extension);
csvToExistingExcel(workbook, csvReader);

/* Write file */
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
workbook.write(fileOutputStream);

/* Close file */
WorkbookUtility.close(workbook, fileOutputStream, csvReader);

return outputFile;
}

/**
* Convert the CSV file into a new sheet of an existing Workbook.<p>
* Note: This method does not call the "write" method of the workbook.
* @param workbook The {@code Workbook} to update
* @param fileInput The input CSV file that will be converted into an Excel file
* @throws IOException If an I/O error has occurred
* @throws CsvValidationException If the CSV file has invalid formatting
* @throws ExtensionNotValidException If the input file extension does not belong to a CSV file
*/
public static void csvToExistingExcel(Workbook workbook, File fileInput) throws IOException, CsvValidationException, ExtensionNotValidException {
/* Check exension */
String csvExt = FilenameUtils.getExtension(fileInput.getName());
isValidCsvExtension(csvExt);

/* Open CSV file */
FileReader fileReader = new FileReader(fileInput);
CSVReader csvReader = new CSVReader(fileReader);
csvToExistingExcel(workbook, csvReader);

/* Close CSV reader */
csvReader.close();
}

/**
* Writes the data present in the CSVReader to a new sheet of an existing Workbook.<p>
* Note: This method does not call the "write" method of the workbook.
* @param workbook The {@code Workbook} to update
* @param csvReader The {@code CSVReader} of the CSV input file
* @throws CsvValidationException If the CSV file has invalid formatting
* @throws IOException If an I/O error has occurred
*/
public static void csvToExistingExcel(Workbook workbook, CSVReader csvReader) throws CsvValidationException, IOException {
Sheet sheet = SheetUtility.create(workbook);

/* Read CSV file */
Expand All @@ -532,15 +603,6 @@ public static File csvToExcel(File fileInput, String path, String filename, Exte
}
cRow++;
}

/* Write file */
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
workbook.write(fileOutputStream);

/* Close file */
WorkbookUtility.close(workbook, fileOutputStream, csvReader);

return outputFile;
}

private static void isValidCsvExtension(String extension) throws ExtensionNotValidException {
Expand Down
1 change: 0 additions & 1 deletion src/main/java/tools/ExcelUtility.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
Expand Down

0 comments on commit a5f3271

Please sign in to comment.