Does anyone here know of any quick, clean way to convert csv files to xls or xlsx files in java?
I have something to manage csv files already in place and I need the extra compatibility for other programs.
Sample code in addition to package names is always well appreciated.
Many thanks,
Justian
Here’s my code thus far. I need to remove the returns («n») from the lines. Some of my cells contain multiple lines of information (a list), so I can use «n» in csv to indicate multiple lines within a cell, but xls treats these as if I mean to put them on a new line.
The code is modified from the internet and a little messy at the moment. You might notice some deprecated methods, as it was written in 2004, and be sure to ignore the terrible return statements. I’m just using S.o.p at the moment for testing and I’ll clean that up later.
package jab.jm.io;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class FileConverter {
public static String ConvertCSVToXLS(String file) throws IOException {
if (file.indexOf(".csv") < 0)
return "Error converting file: .csv file not given.";
String name = FileManager.getFileNameFromPath(file, false);
ArrayList<ArrayList<String>> arList = new ArrayList<ArrayList<String>>();
ArrayList<String> al = null;
String thisLine;
DataInputStream myInput = new DataInputStream(new FileInputStream(file));
while ((thisLine = myInput.readLine()) != null) {
al = new ArrayList<String>();
String strar[] = thisLine.split(",");
for (int j = 0; j < strar.length; j++) {
// My Attempt (BELOW)
String edit = strar[j].replace('n', ' ');
al.add(edit);
}
arList.add(al);
System.out.println();
}
try {
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for (int k = 0; k < arList.size(); k++) {
ArrayList<String> ardata = (ArrayList<String>) arList.get(k);
HSSFRow row = sheet.createRow((short) 0 + k);
for (int p = 0; p < ardata.size(); p++) {
System.out.print(ardata.get(p));
HSSFCell cell = row.createCell((short) p);
cell.setCellValue(ardata.get(p).toString());
}
}
FileOutputStream fileOut = new FileOutputStream(
FileManager.getCleanPath() + "/converted files/" + name
+ ".xls");
hwb.write(fileOut);
fileOut.close();
System.out.println(name + ".xls has been generated");
} catch (Exception ex) {
}
return "";
}
}
java-CSV-to-Excel
Usage
The executable jar is in the ‘dist’ directory
java -jar java-csv-to-excel-jar-with-dependencies.jar -t [xlsx|xls] -o [outfile] -d [delimiter] -e [input encoding] -i [infile1:infile2:infile3...]
Example Usage
Pipe Delimited CSVs
java -jar java-csv-to-excel-jar-with-dependencies.jar -t xlsx -o myoutfile -d "|" -e UTF-8 -i mysheet1.txt:mysheet2.txt:mysheet3.txt
Using same output name as input name
java -jar java-csv-to-excel-jar-with-dependencies.jar -t xlsx -o /home/toto/doc/myfile.csv -d "|" -e UTF-8 -i /home/toto/doc/myfile.csv
Will create a file with name ‘/home/toto/doc/myfile.csv.xlsx’
Troubleshooting:
- «Command not found.»: If you are using a pipe delimiter it must be escaped with a slash. E.g. «|».
- «(No such file or directory)»: Check you have the correct input/output file paths
l
HOWTO build a new executable jar
mvn clean compile assembly:single
Hello readers, in this tutorial, we are going to implement the Csv to Excel file conversion by using the Apache POI library. This tutorial will show developers how to write large data to an excel file using SXSSF
.
1. Introduction
SXSSF
(Package Name: org.apache.poi.xssf.streaming
) is an API compatible streaming extension of XSSF
to be used when very large spreadsheets have to be produced, and the heap space is limited. SXSSF
achieves its low memory footprint by limiting access to the rows that are within a sliding window, while XSSF
gives access to all rows in the document. Older rows that are no longer in the window become inaccessible, as they are written to the disk.
In the auto-flush mode the size of the access window can be specified, to hold a certain number of rows in the memory. When that value is reached, the creation of an additional row causes the row with the lowest index to be removed from the access window and written to the disk. Do remember, the window size can be set to grow dynamically i.e. it can be trimmed periodically by an explicit call to the flushRows(int keepRows)
method needed. Due to the streaming nature of the implementation, there are the following limitations when compared to the XSSF
.
- Only a limited number of rows are accessible at a point in time
- The
sheetObj.clone()
method is not supported - Formula evaluation is not supported
Note: If developers are getting the java.lang.OutOfMemoryError
exception, then the developers must use the low-memory footprint SXSSF
API implementation.
Now, open up the Eclipse Ide and let’s see how to implement this conversion with the help of Apache POI library!
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>CsvToExcel</groupId> <artifactId>CsvToExcel</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> </project>
Developers can start adding the dependencies that they want to like OpenCsv, Apache POI etc. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Maven Dependencies
Here, we specify the dependencies for the OpenCsv, Apache POI, and Log4j. The rest dependencies will be automatically resolved by the Maven framework and the updated file will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>CsvToExcel</groupId> <artifactId>CsvToExcel</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang --> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/com.opencsv/opencsv --> <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>3.9</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
3.2 Java Class Creation
Let’s create the required Java files. Right-click on the src/main/java
folder, New -> Package
.
A new pop window will open where we will enter the package name as: com.jcg.csv2excel
.
Once the package is created in the application, we will need to create the implementation class and the main class. Right-click on the newly created package: New -> Class
.
A new pop window will open and enter the file name as: CsvToExcel
. The utility class will be created inside the package: com.jcg.csv2excel
.
Repeat the step (i.e. Fig. 7) and enter the filename as: AppMain
. The main class will be created inside the package: com.jcg.csv2excel
.
3.2.1 Implementation of Utility Class
The complete Java code to convert a Csv file to the Excel format is provided below. Let’s see the simple code snippet that follows this implementation.
CsvToExcel.java
package com.jcg.csv2excel; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import org.apache.commons.lang.math.NumberUtils; import org.apache.log4j.Logger; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import com.opencsv.CSVReader; public class CsvToExcel { public static final char FILE_DELIMITER = ','; public static final String FILE_EXTN = ".xlsx"; public static final String FILE_NAME = "EXCEL_DATA"; private static Logger logger = Logger.getLogger(CsvToExcel.class); public static String convertCsvToXls(String xlsFileLocation, String csvFilePath) { SXSSFSheet sheet = null; CSVReader reader = null; Workbook workBook = null; String generatedXlsFilePath = ""; FileOutputStream fileOutputStream = null; try { /**** Get the CSVReader Instance & Specify The Delimiter To Be Used ****/ String[] nextLine; reader = new CSVReader(new FileReader(csvFilePath), FILE_DELIMITER); workBook = new SXSSFWorkbook(); sheet = (SXSSFSheet) workBook.createSheet("Sheet"); int rowNum = 0; logger.info("Creating New .Xls File From The Already Generated .Csv File"); while((nextLine = reader.readNext()) != null) { Row currentRow = sheet.createRow(rowNum++); for(int i=0; i < nextLine.length; i++) { if(NumberUtils.isDigits(nextLine[i])) { currentRow.createCell(i).setCellValue(Integer.parseInt(nextLine[i])); } else if (NumberUtils.isNumber(nextLine[i])) { currentRow.createCell(i).setCellValue(Double.parseDouble(nextLine[i])); } else { currentRow.createCell(i).setCellValue(nextLine[i]); } } } generatedXlsFilePath = xlsFileLocation + FILE_NAME + FILE_EXTN; logger.info("The File Is Generated At The Following Location?= " + generatedXlsFilePath); fileOutputStream = new FileOutputStream(generatedXlsFilePath.trim()); workBook.write(fileOutputStream); } catch(Exception exObj) { logger.error("Exception In convertCsvToXls() Method?= " + exObj); } finally { try { /**** Closing The Excel Workbook Object ****/ workBook.close(); /**** Closing The File-Writer Object ****/ fileOutputStream.close(); /**** Closing The CSV File-ReaderObject ****/ reader.close(); } catch (IOException ioExObj) { logger.error("Exception While Closing I/O Objects In convertCsvToXls() Method?= " + ioExObj); } } return generatedXlsFilePath; } }
3.2.2 Implementation of Main Class
This is the main class required to execute the program and test the conversion functionality. Add the following code to it.
AppMain.java
package com.jcg.csv2excel; import org.apache.log4j.Logger; public class AppMain { private static Logger logger = Logger.getLogger(AppMain.class); public static void main(String[] args) { String xlsLoc = "config/", csvLoc = "config/sample.csv", fileLoc = ""; fileLoc = CsvToExcel.convertCsvToXls(xlsLoc, csvLoc); logger.info("File Location Is?= " + fileLoc); } }
4. Run the Application
To run the application, Right-click on the AppMain
class -> Run As -> Java Application
. Developers can debug the example and see what happens after every step!
5. Project Demo
The application shows the following as output where the Csv is successfully converted to Excel and is successfully placed in the project’s config
folder.
That’s all for this post. Happy Learning!!
6. Conclusion
This tutorial used the Apache POI libraries to demonstrate a simple Csv to Excel file conversion. That’s all for this tutorial and I hope this article served you whatever you were looking for.
7. Download the Eclipse Project
This was an example of Csv to Excel file conversion for the beginners.
Download
You can download the full source code of this example here: CsvToExcel
CSV file is an abbreviation of Comma-separated values. It is a type of delimited text file. A delimiter is a sequence of one or more characters to specify the boundary between separate, independent regions in plain text or other data streams. Since the delimiter in CSV file is Comma that separates fields in a row, therefore it is called Comma-separated values. Aspose.Cells for Java is capable of loading the CSV file and converting it to various Excel formats e.g. XLS, XLSX, XLSM, XLSB etc. It can also convert CSV file into non-Excel formats e.g. HTML, PDF etc. You can also convert your CSV file into Image formats e.g. JPG, PNG, TIFF etc.
Convert CSV to Excel Formats
In this document, we will explain how to convert your CSV file into various Excel formats e.g. XLS, XLSX, XLSM, XLSB etc. Please download the sample CSV file used inside the code as shown in this image for your reference.
Convert CSV to XLS format
XLS is a very important Excel format. It is available since the Excel 2003 or may be earlier and still lots of Excel documents are saved in this format. XLS format is a sort of binary format and it can also contain Macros or VBA. Aspose.Cells which is an API provided by Aspose can convert your CSV file to XLS format using the following code.
// Directory path for input and output files. | |
String dirPath = «D:\Download\»; | |
// Load your sample CSV file inside the Workbook object. | |
com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(dirPath + «sampleConvertCSVToExcelFormats.csv»); | |
// Save CSV file to XLS format. | |
wb.save(dirPath + «outputConvertCSVToExcelFormats.xls», SaveFormat.EXCEL_97_TO_2003); |
The following screenshot shows the output XLS file generated by the above code for your reference.
Convert CSV to XLSX format
XLSX is a newer Microsoft Excel Open XML Format. It is kind of XML based format and stores the spreadsheet data in XML structures. It is widely used format since Excel 2007 and till today. Normally, you should save your Excel files in XLSX format rather than XLS format. Besides, XLS can have at most 65536 rows while XLSX can have 1048576 rows which is far greater than XLS. Similarly, XLS can have 256 columns and XLSX can have 16384 columns which is again far greater than XLS.
However, unlike XLS format, XLSX format cannot contain Macros or VBA. If you want to use XLSX format benefits and also want to use Macros or VBA, then you should use XLSM format which is actually a Macro-Enabled XLSX format. The following sample code explains how you can convert your CSV file to XLSX format using Aspose.Cells API.
// Directory path for input and output files. | |
String dirPath = «D:\Download\»; | |
// Load your sample CSV file inside the Workbook object. | |
com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(dirPath + «sampleConvertCSVToExcelFormats.csv»); | |
// Save CSV file to XLSX format. | |
wb.save(dirPath + «outputConvertCSVToExcelFormats.xlsx», SaveFormat.XLSX); |
The following screenshot shows the output XLSX file generated by the above code for your reference.
Convert CSV to XLSM format
XLSM format is same as XLSX but it supports VBA or Macros. It is therefore called Macro-Enabled XLSX format. The following sample code explains how you can convert your CSV file to XLSM format using Aspose.Cells API.
// Directory path for input and output files. | |
String dirPath = «D:\Download\»; | |
// Load your sample CSV file inside the Workbook object. | |
com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(dirPath + «sampleConvertCSVToExcelFormats.csv»); | |
// Save CSV file to XLSM format. | |
wb.save(dirPath + «outputConvertCSVToExcelFormats.xlsm», SaveFormat.XLSM); |
The following screenshot shows the output XLSM file generated by the above code for your reference.
Convert CSV to XLSB format
XLSB format is same as XLSM format but unlike XML-based format, it is a binary format. Binary formats are often used to save the file size which is useful in scenarios where user needs to transfer files on network.
// Directory path for input and output files. | |
String dirPath = «D:\Download\»; | |
// Load your sample CSV file inside the Workbook object. | |
com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(dirPath + «sampleConvertCSVToExcelFormats.csv»); | |
// Save CSV file to XLSB format. | |
wb.save(dirPath + «outputConvertCSVToExcelFormats.xlsb», SaveFormat.XLSB); |
The following screenshot shows the output XLSB file generated by the above code for your reference.
Join the DZone community and get the full member experience.
Join For Free
Excel is the household name in spreadsheet software for good reason. With an emphasis on user experience and interfacing, clients will feel comfortable with the familiar layout and formatting of an Excel spreadsheet. For this reason, when displaying data to your customer base, Excel is king.
An issue may arise, however, when data is stored as a CSV file rather than Excel. Many developers choose to store data as a CSV, due to its simplicity and expedience. However, while it is possible to open a CSV file in Excel, the manual process is often not the ideal solution for many businesses that rely on automated systems. Furthermore, while the CSV file format is familiar to developers and those who work with data input and analysis, clients may not recognize information in the way that it is meant to be perceived. This leads to trouble when the information being conveyed is of imminent importance to both your organization and your customers.
Luckily, this problem can be solved easily, as Cloudmersive has a solution for that.
Using one of our APIs, you can:
-
Quickly and efficiently convert your CSV files into XLSX using Java, and
-
Convert multiple CSV files into a group of worksheets in a single Excel spreadsheet.
First, however, we must start with some initial setup and installation steps.
Our library installation begins with a repository reference for our Maven POM file, to add the library.
Then, add a dependency reference in pom.xml:
Alternatively, to install with Gradle, add it in your root build.gradle at the end of repositories:
And add the dependency in build.gradle:
After these initial steps are completed, our focus should turn to the controller, where our imports should be added to the top of the file.
Then, we will call our function. The code shown below provides an example of how to complete this process.
Following these steps, you have set yourself up for success in converting CSV files into XLSX spreadsheets.
However, what happens when you need to covert multiple CSVs into one Excel workbook? The API we are going to show you next will split each CSV file you are converting into separate worksheets within the same Excel file.
The function of this process is quite similar and follows the same procedures for install and setup, as well as the import classes.
The first change occurs when we call our function, convertDocumentCsvMultiToXlsx, as shown below.
With this, you can easily add multiple CSV files into your Excel document by simply adding more input lines, as well as adding names for each worksheet within the function.
Cloudmersive takes pride in helping you solve any problems that may arise as we move into the digital age, especially when our systems can aid in bridging the gap between your business and your clients. If you find yourself needing additional help or have questions regarding any of our APIs, we will be happy to offer our assistance.
CSV
Java (programming language)
Convert (command)
Opinions expressed by DZone contributors are their own.
Trending
-
What Will Come After Agile?
-
Application Architecture Design Principles
-
Productivity: Noise Is the Problem
-
Creating Scalable OpenAI GPT Applications in Java