Skip to content

Commit 2f525e5

Browse files
committed
I added a method to convert an excel file to CSV. I added a method to check if there are any sheets based on their position or name. Other methods for closing a workbook and the various classes of streams.
1 parent 2af557a commit 2f525e5

File tree

9 files changed

+147
-2
lines changed

9 files changed

+147
-2
lines changed

pom.xml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
<version>1.0-SNAPSHOT</version>
1010
<packaging>jar</packaging>
1111
<name>java-excel-tools</name>
12-
<description>Library with tools to work with excel files</description>
12+
<description>Library with tools to work with Excel files</description>
1313

1414
<properties>
1515
<maven.compiler.source>17</maven.compiler.source>
@@ -39,5 +39,10 @@
3939
<artifactId>commons-beanutils</artifactId>
4040
<version>1.9.4</version>
4141
</dependency>
42+
<dependency>
43+
<groupId>com.opencsv</groupId>
44+
<artifactId>opencsv</artifactId>
45+
<version>5.7.1</version>
46+
</dependency>
4247
</dependencies>
4348
</project>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package samples.convertExcelFileToCsvFile;
2+
3+
import tools.implementations.ExcelConverterImpl;
4+
import tools.interfaces.ExcelConverter;
5+
6+
import java.io.File;
7+
8+
public class Main {
9+
10+
public static void main(String[] args) {
11+
12+
ExcelConverter excelConverter = new ExcelConverterImpl();
13+
File excelFile = new File("./src/main/resources/employee.xlsx");
14+
15+
try {
16+
System.out.println("Start the conversion...");
17+
File csvFile = excelConverter.excelToCsv(excelFile, "./src/main/resources/", "employee", "Employee");
18+
System.out.println("The file is ready. Path: " + csvFile.getAbsolutePath());
19+
} catch (Exception e) {
20+
System.err.println("There was an error. Check the console");
21+
throw new RuntimeException(e);
22+
}
23+
}
24+
}

src/main/java/samples/sheetSample/Main.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package samples.sheetSample;
22

3+
import org.apache.poi.ss.usermodel.Workbook;
4+
import tools.implementations.ExcelWorkbookUtilsImpl;
35
import tools.interfaces.ExcelSheetUtils;
46
import tools.implementations.ExcelSheetUtilsImpl;
7+
import tools.interfaces.ExcelWorkbookUtils;
58

69
import java.io.File;
710
import java.util.List;
@@ -10,6 +13,7 @@ public class Main {
1013

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

16+
ExcelWorkbookUtils excelWorkbookUtils = new ExcelWorkbookUtilsImpl();
1317
ExcelSheetUtils excelSheetUtils = new ExcelSheetUtilsImpl();
1418
File file = new File("./src/main/resources/employee.xlsx");
1519

@@ -22,6 +26,14 @@ public static void main(String[] args) {
2226
System.out.println("Sheet index: " + sheetIndex);
2327
String sheetName = excelSheetUtils.getNameByIndex(file, 0);
2428
System.out.println("Sheet name: " + sheetName);
29+
30+
Workbook workbook = excelWorkbookUtils.open(file);
31+
String sheetNameTest = "test";
32+
int sheetIndexTest = 0;
33+
Boolean isPresentByName = excelSheetUtils.isPresent(workbook, sheetNameTest);
34+
System.out.println("Sheet is: " + sheetNameTest + " is present: " + isPresentByName);
35+
Boolean isPresentByPosition = excelSheetUtils.isPresent(workbook, 0);
36+
System.out.println("Sheet index: " + sheetIndexTest + " is present: " + isPresentByPosition);
2537
} catch (Exception e) {
2638
System.err.println("There was an error. Check the console");
2739
throw new RuntimeException(e);

src/main/java/tools/implementations/ExcelConverterImpl.java

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import annotations.ExcelBodyStyle;
44
import annotations.ExcelField;
55
import annotations.ExcelHeaderStyle;
6+
import com.opencsv.CSVWriter;
67
import enums.ExcelExtension;
78
import exceptions.*;
89
import org.apache.commons.beanutils.PropertyUtils;
@@ -160,6 +161,63 @@ public List<?> excelToObjects(File file, Class<?> clazz, String sheetName) throw
160161
return resultList;
161162
}
162163

164+
@Override
165+
public File excelToCsv(File fileInput) throws FileAlreadyExistsException, OpenWorkbookException, SheetNotFoundException, ExtensionNotValidException, IOException {
166+
return excelToCsv(fileInput, System.getProperty("java.io.tmpdir"), fileInput.getName().split("\\.")[0].trim(), null);
167+
}
168+
169+
@Override
170+
public File excelToCsv(File fileInput, String sheetName) throws FileAlreadyExistsException, OpenWorkbookException, SheetNotFoundException, ExtensionNotValidException, IOException {
171+
return excelToCsv(fileInput, System.getProperty("java.io.tmpdir"), fileInput.getName().split("\\.")[0].trim(), sheetName);
172+
}
173+
174+
@Override
175+
public File excelToCsv(File fileInput, String path, String filename) throws FileAlreadyExistsException, OpenWorkbookException, SheetNotFoundException, ExtensionNotValidException, IOException {
176+
return excelToCsv(fileInput, path, filename, null);
177+
}
178+
179+
@Override
180+
public File excelToCsv(File fileInput, String path, String filename, String sheetName) throws ExtensionNotValidException, IOException, OpenWorkbookException, SheetNotFoundException, FileAlreadyExistsException {
181+
/* Check extension */
182+
ExcelUtils excelUtils = new ExcelUtilsImpl();
183+
String extension = excelUtils.checkExtension(fileInput.getName());
184+
185+
/* Open file excel */
186+
ExcelWorkbookUtils excelWorkbookUtils = new ExcelWorkbookUtilsImpl();
187+
FileInputStream fileInputStream = new FileInputStream(fileInput);
188+
Workbook workbook = excelWorkbookUtils.open(fileInputStream, extension);
189+
ExcelSheetUtils excelSheetUtils = new ExcelSheetUtilsImpl();
190+
Sheet sheet = (sheetName == null || sheetName.isEmpty())
191+
? excelSheetUtils.open(workbook)
192+
: excelSheetUtils.open(workbook, sheetName);
193+
194+
/* Create output file */
195+
String pathname = this.getPathname(path, filename, "csv");
196+
File csvFile = new File(pathname);
197+
198+
if (csvFile.exists()) {
199+
throw new FileAlreadyExistsException("There is already a file with this pathname: " + csvFile.getAbsolutePath());
200+
}
201+
202+
/* Write output file */
203+
FileWriter fileWriter = new FileWriter(csvFile);
204+
CSVWriter csvWriter = new CSVWriter(fileWriter);
205+
206+
DataFormatter formatter = new DataFormatter(true);
207+
for (Row row : sheet) {
208+
List<String> data = new LinkedList<>();
209+
for (int i = 0; i < row.getLastCellNum(); i++) {
210+
data.add(formatter.formatCellValue(row.getCell(i)));
211+
}
212+
csvWriter.writeNext(data.toArray(data.toArray(new String[0])));
213+
}
214+
215+
/* Close file */
216+
excelWorkbookUtils.close(workbook, fileInputStream, csvWriter);
217+
218+
return csvFile;
219+
}
220+
163221
private Map<Integer, String> getHeaderNames(Sheet sheet, Field[] fields) throws HeaderNotPresentException {
164222
Map<String, String> fieldNames = new HashMap<>();
165223
for (Field field : fields) {
@@ -323,11 +381,15 @@ private void setAutoSizeColumn(Sheet sheet, Field[] fields, Class<?> clazz) {
323381
}
324382

325383
private String getPathname(String path, String filename, ExcelExtension extension) {
384+
return getPathname(path, filename, extension.getExt());
385+
}
386+
387+
private String getPathname(String path, String filename, String extension) {
326388
path = path.replaceAll("\\\\", "/");
327389
if (path.charAt(path.length() - 1) != '/') {
328390
path += '/';
329391
}
330392

331-
return path + filename + '.' + extension.getExt();
393+
return path + filename + '.' + extension;
332394
}
333395
}

src/main/java/tools/implementations/ExcelSheetUtilsImpl.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,4 +208,14 @@ public Sheet openOrCreate(Workbook workbook, String sheetName) {
208208
Sheet sheet = workbook.getSheet(sheetName);
209209
return sheet == null ? workbook.createSheet(sheetName) : sheet;
210210
}
211+
212+
@Override
213+
public Boolean isPresent(Workbook workbook, String sheetName) {
214+
return workbook.getSheet(sheetName) != null;
215+
}
216+
217+
@Override
218+
public Boolean isPresent(Workbook workbook, Integer position) {
219+
return workbook.getSheetAt(position) != null;
220+
}
211221
}

src/main/java/tools/implementations/ExcelWorkbookUtilsImpl.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package tools.implementations;
22

3+
import com.opencsv.CSVWriter;
34
import enums.ExcelExtension;
45
import exceptions.ExtensionNotValidException;
56
import exceptions.OpenWorkbookException;
@@ -87,4 +88,18 @@ public void close(Workbook workbook, FileOutputStream fileOutputStream) throws I
8788
workbook.close();
8889
fileOutputStream.close();
8990
}
91+
92+
@Override
93+
public void close(Workbook workbook, FileOutputStream fileOutputStream, FileInputStream fileInputStream) throws IOException {
94+
workbook.close();
95+
fileInputStream.close();
96+
fileOutputStream.close();
97+
}
98+
99+
@Override
100+
public void close(Workbook workbook, FileInputStream fileInputStream, CSVWriter writer) throws IOException {
101+
workbook.close();
102+
fileInputStream.close();
103+
writer.close();
104+
}
90105
}

src/main/java/tools/interfaces/ExcelConverter.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,12 @@ public interface ExcelConverter {
3737
List<?> excelToObjects(File file, Class<?> clazz) throws ExtensionNotValidException, IOException, OpenWorkbookException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SheetNotFoundException, HeaderNotPresentException;
3838

3939
List<?> excelToObjects(File file, Class<?> clazz, String sheetName) throws ExtensionNotValidException, IOException, OpenWorkbookException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException, SheetNotFoundException, HeaderNotPresentException;
40+
41+
File excelToCsv(File fileInput) throws FileAlreadyExistsException, OpenWorkbookException, SheetNotFoundException, ExtensionNotValidException, IOException;
42+
43+
File excelToCsv(File fileInput, String sheetName) throws FileAlreadyExistsException, OpenWorkbookException, SheetNotFoundException, ExtensionNotValidException, IOException;
44+
45+
File excelToCsv(File fileInput, String path, String filename) throws FileAlreadyExistsException, OpenWorkbookException, SheetNotFoundException, ExtensionNotValidException, IOException;
46+
47+
File excelToCsv(File fileInput, String path, String filename, String sheetName) throws ExtensionNotValidException, IOException, OpenWorkbookException, SheetNotFoundException, FileAlreadyExistsException;
4048
}

src/main/java/tools/interfaces/ExcelSheetUtils.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,8 @@ public interface ExcelSheetUtils {
4141
Sheet open(Workbook workbook, Integer position) throws SheetNotFoundException;
4242

4343
Sheet openOrCreate(Workbook workbook, String sheetName);
44+
45+
Boolean isPresent(Workbook workbook, String sheetName);
46+
47+
Boolean isPresent(Workbook workbook, Integer position);
4448
}

src/main/java/tools/interfaces/ExcelWorkbookUtils.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package tools.interfaces;
22

3+
import com.opencsv.CSVWriter;
34
import enums.ExcelExtension;
45
import exceptions.ExtensionNotValidException;
56
import exceptions.OpenWorkbookException;
@@ -24,4 +25,8 @@ public interface ExcelWorkbookUtils {
2425
void close(Workbook workbook, FileInputStream fileInputStream) throws IOException;
2526

2627
void close(Workbook workbook, FileOutputStream fileOutputStream) throws IOException;
28+
29+
void close(Workbook workbook, FileOutputStream fileOutputStream, FileInputStream fileInputStream) throws IOException;
30+
31+
void close(Workbook workbook, FileInputStream fileInputStream, CSVWriter writer) throws IOException;
2732
}

0 commit comments

Comments
 (0)