Skip to content

Commit 14f14ce

Browse files
committed
Added new methods to convert Excel to CSV
1 parent 102fab6 commit 14f14ce

File tree

3 files changed

+145
-2
lines changed

3 files changed

+145
-2
lines changed

src/main/java/io/github/mbenincasa/javaexcelutils/samples/convertExcelFileToCsvFile/Main.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import io.github.mbenincasa.javaexcelutils.tools.Converter;
44

55
import java.io.File;
6+
import java.util.Map;
67

78
public class Main {
89

@@ -12,8 +13,11 @@ public static void main(String[] args) {
1213

1314
try {
1415
System.out.println("Start the conversion...");
15-
File csvFile = Converter.excelToCsv(excelFile, "./src/main/resources/", "employee", "Employee");
16-
System.out.println("The file is ready. Path: " + csvFile.getAbsolutePath());
16+
Map<String, File> fileMap = Converter.excelToCsvFile(excelFile, "./src/main/resources/");
17+
System.out.println("... completed");
18+
for (Map.Entry<String, File> entry : fileMap.entrySet()) {
19+
System.out.println("The file is ready. Path: " + entry.getValue().getAbsolutePath());
20+
}
1721
} catch (Exception e) {
1822
System.err.println("There was an error. Check the console");
1923
throw new RuntimeException(e);

src/main/java/io/github/mbenincasa/javaexcelutils/tools/Converter.java

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,7 @@ public static Map<String, Stream<?>> excelStreamToObjects(InputStream inputStrea
605605
/**
606606
* Convert an Excel file into a CSV file<p>
607607
* The default path is that of the temporary folder. By default, the first sheet is chosen and the filename will be the same as the input file if not specified
608+
* @deprecated since version 0.4.0
608609
* @param fileInput The input Excel file that will be converted into a CSV file
609610
* @return A CSV file that contains the same lines as the Excel file
610611
* @throws FileAlreadyExistsException If the destination file already exists
@@ -613,13 +614,15 @@ public static Map<String, Stream<?>> excelStreamToObjects(InputStream inputStrea
613614
* @throws ExtensionNotValidException If the input file extension does not belong to an Excel file
614615
* @throws IOException If an I/O error has occurred
615616
*/
617+
@Deprecated
616618
public static File excelToCsv(File fileInput) throws FileAlreadyExistsException, OpenWorkbookException, SheetNotFoundException, ExtensionNotValidException, IOException {
617619
return excelToCsv(fileInput, System.getProperty("java.io.tmpdir"), fileInput.getName().split("\\.")[0].trim(), null);
618620
}
619621

620622
/**
621623
* Convert an Excel file into a CSV file<p>
622624
* The default path is that of the temporary folder. By default, the first sheet is chosen and the filename will be the same as the input file if not specified
625+
* @deprecated since version 0.4.0
623626
* @param fileInput The input Excel file that will be converted into a CSV file
624627
* @param sheetName The name of the sheet to open
625628
* @return A CSV file that contains the same lines as the Excel file
@@ -629,13 +632,15 @@ public static File excelToCsv(File fileInput) throws FileAlreadyExistsException,
629632
* @throws ExtensionNotValidException If the input file extension does not belong to an Excel file
630633
* @throws IOException If an I/O error has occurred
631634
*/
635+
@Deprecated
632636
public static File excelToCsv(File fileInput, String sheetName) throws FileAlreadyExistsException, OpenWorkbookException, SheetNotFoundException, ExtensionNotValidException, IOException {
633637
return excelToCsv(fileInput, System.getProperty("java.io.tmpdir"), fileInput.getName().split("\\.")[0].trim(), sheetName);
634638
}
635639

636640
/**
637641
* Convert an Excel file into a CSV file<p>
638642
* By default, the first sheet is chosen
643+
* @deprecated since version 0.4.0
639644
* @param fileInput The input Excel file that will be converted into a CSV file
640645
* @param path The destination path of the output file
641646
* @param filename The name of the output file without the extension
@@ -646,12 +651,14 @@ public static File excelToCsv(File fileInput, String sheetName) throws FileAlrea
646651
* @throws ExtensionNotValidException If the input file extension does not belong to an Excel file
647652
* @throws IOException If an I/O error has occurred
648653
*/
654+
@Deprecated
649655
public static File excelToCsv(File fileInput, String path, String filename) throws FileAlreadyExistsException, OpenWorkbookException, SheetNotFoundException, ExtensionNotValidException, IOException {
650656
return excelToCsv(fileInput, path, filename, null);
651657
}
652658

653659
/**
654660
* Convert an Excel file into a CSV file
661+
* @deprecated since version 0.4.0
655662
* @param fileInput The input Excel file that will be converted into a CSV file
656663
* @param path The destination path of the output file
657664
* @param filename The name of the output file without the extension
@@ -663,6 +670,7 @@ public static File excelToCsv(File fileInput, String path, String filename) thro
663670
* @throws ExtensionNotValidException If the input file extension does not belong to an Excel file
664671
* @throws IOException If an I/O error has occurred
665672
*/
673+
@Deprecated
666674
public static File excelToCsv(File fileInput, String path, String filename, String sheetName) throws ExtensionNotValidException, IOException, OpenWorkbookException, SheetNotFoundException, FileAlreadyExistsException {
667675
/* Open file excel */
668676
ExcelWorkbook excelWorkbook = ExcelWorkbook.open(fileInput);
@@ -697,6 +705,74 @@ public static File excelToCsv(File fileInput, String path, String filename, Stri
697705
return csvFile;
698706
}
699707

708+
public static Map<String, byte[]> excelToCsvByte(byte[] bytes) throws OpenWorkbookException, IOException {
709+
/* Open InputStream */
710+
InputStream inputStream = new ByteArrayInputStream(bytes);
711+
Map<String, byte[]> byteArrayMap = new HashMap<>();
712+
713+
Map<String, OutputStream> outputStreamMap = excelToCsvStream(inputStream);
714+
715+
/* iterate all the outputStream */
716+
for (Map.Entry<String, OutputStream> entry : outputStreamMap.entrySet()) {
717+
ByteArrayOutputStream baos = (ByteArrayOutputStream) entry.getValue();
718+
byteArrayMap.put(entry.getKey(), baos.toByteArray());
719+
}
720+
721+
return byteArrayMap;
722+
}
723+
724+
public static Map<String, File> excelToCsvFile(File excelFile, String path) throws IOException, OpenWorkbookException {
725+
/* Open InputStream */
726+
FileInputStream fileInputStream = new FileInputStream(excelFile);
727+
Map<String, File> fileMap = new HashMap<>();
728+
729+
Map<String, OutputStream> outputStreamMap = excelToCsvStream(fileInputStream);
730+
731+
/* iterate all the outputStream */
732+
for (Map.Entry<String, OutputStream> entry : outputStreamMap.entrySet()) {
733+
String pathname = path + "/" + entry.getKey() + "." + Extension.CSV.getExt();
734+
FileOutputStream fileOutputStream = new FileOutputStream(pathname);
735+
ByteArrayOutputStream baos = (ByteArrayOutputStream) entry.getValue();
736+
fileOutputStream.write(baos.toByteArray());
737+
File file = new File(pathname);
738+
fileMap.put(entry.getKey(), file);
739+
fileOutputStream.close();
740+
}
741+
742+
return fileMap;
743+
}
744+
745+
public static Map<String, OutputStream> excelToCsvStream(InputStream excelStream) throws OpenWorkbookException, IOException {
746+
/* Open file excel */
747+
ExcelWorkbook excelWorkbook = new ExcelWorkbook(excelStream);
748+
List<ExcelSheet> excelSheets = excelWorkbook.getSheets();
749+
750+
Map<String, OutputStream> map = new HashMap<>();
751+
752+
/* Iterate all the Sheets */
753+
for (ExcelSheet excelSheet : excelSheets) {
754+
OutputStream outputStream = new ByteArrayOutputStream();
755+
Writer writer = new OutputStreamWriter(outputStream);
756+
CSVWriter csvWriter = new CSVWriter(writer);
757+
758+
DataFormatter formatter = new DataFormatter(true);
759+
for (ExcelRow excelRow : excelSheet.getRows()) {
760+
List<String> data = new LinkedList<>();
761+
for (ExcelCell excelCell : excelRow.getCells()) {
762+
data.add(formatter.formatCellValue(excelCell.getCell()));
763+
}
764+
csvWriter.writeNext(data.toArray(data.toArray(new String[0])));
765+
}
766+
csvWriter.close();
767+
map.put(excelSheet.getName(), outputStream);
768+
}
769+
770+
/* Close workbook */
771+
excelWorkbook.close();
772+
773+
return map;
774+
}
775+
700776
/**
701777
* Convert a CSV file into an Excel file<p>
702778
* The default path is that of the temporary folder. By default, the filename will be the same as the input file if not specified and the extension is XLSX

src/test/java/io/github/mbenincasa/javaexcelutils/tools/ConverterTest.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,4 +605,67 @@ void excelStreamToObjects() throws IOException, OpenWorkbookException, SheetNotF
605605
Assertions.assertEquals(20, people.get(0).getAge());
606606
fileInputStream.close();
607607
}
608+
609+
@Test
610+
void excelToCsvByte() throws IOException, OpenWorkbookException, CsvValidationException {
611+
byte[] bytes = Files.readAllBytes(excelFile.toPath());
612+
Map<String, byte[]> byteMap = Converter.excelToCsvByte(bytes);
613+
File csvFile = new File("person.csv");
614+
FileOutputStream fileOutputStream = new FileOutputStream(csvFile);
615+
fileOutputStream.write(byteMap.get("Person"));
616+
FileReader fileReader = new FileReader(csvFile);
617+
CSVReader csvReader = new CSVReader(fileReader);
618+
String[] values = csvReader.readNext();
619+
Assertions.assertEquals("LAST NAME", values[0]);
620+
Assertions.assertEquals("NAME", values[1]);
621+
Assertions.assertEquals("AGE", values[2]);
622+
values = csvReader.readNext();
623+
Assertions.assertEquals("Rossi", values[0]);
624+
Assertions.assertEquals("Mario", values[1]);
625+
Assertions.assertEquals(20, Integer.parseInt(values[2]));
626+
fileOutputStream.close();
627+
csvReader.close();
628+
csvFile.delete();
629+
}
630+
631+
@Test
632+
void excelToCsvFile() throws OpenWorkbookException, IOException, CsvValidationException {
633+
Map<String, File> fileMap = Converter.excelToCsvFile(excelFile, "./src/");
634+
FileReader fileReader = new FileReader(fileMap.get("Person"));
635+
CSVReader csvReader = new CSVReader(fileReader);
636+
String[] values = csvReader.readNext();
637+
Assertions.assertEquals("LAST NAME", values[0]);
638+
Assertions.assertEquals("NAME", values[1]);
639+
Assertions.assertEquals("AGE", values[2]);
640+
values = csvReader.readNext();
641+
Assertions.assertEquals("Rossi", values[0]);
642+
Assertions.assertEquals("Mario", values[1]);
643+
Assertions.assertEquals(20, Integer.parseInt(values[2]));
644+
csvReader.close();
645+
fileMap.get("Person").delete();
646+
}
647+
648+
@Test
649+
void excelToCsvStream() throws IOException, OpenWorkbookException, CsvValidationException {
650+
FileInputStream fileInputStream = new FileInputStream(excelFile);
651+
Map<String, OutputStream> outputStreamMap = Converter.excelToCsvStream(fileInputStream);
652+
FileOutputStream fileOutputStream = new FileOutputStream("person.csv");
653+
ByteArrayOutputStream baos = (ByteArrayOutputStream) outputStreamMap.get("Person");
654+
fileOutputStream.write(baos.toByteArray());
655+
File csvFile = new File("person.csv");
656+
FileReader fileReader = new FileReader(csvFile);
657+
CSVReader csvReader = new CSVReader(fileReader);
658+
String[] values = csvReader.readNext();
659+
Assertions.assertEquals("LAST NAME", values[0]);
660+
Assertions.assertEquals("NAME", values[1]);
661+
Assertions.assertEquals("AGE", values[2]);
662+
values = csvReader.readNext();
663+
Assertions.assertEquals("Rossi", values[0]);
664+
Assertions.assertEquals("Mario", values[1]);
665+
Assertions.assertEquals(20, Integer.parseInt(values[2]));
666+
fileOutputStream.close();
667+
csvReader.close();
668+
csvFile.delete();
669+
fileInputStream.close();
670+
}
608671
}

0 commit comments

Comments
 (0)