[ACCEPTED]-How to create an Excel file based on CSV file using Java?-csv

Accepted answer
Score: 24

I suggest you use the Apache POI framework (specifically the 6 HSSF / XSSF API) for writing out the XLS file.

For reading 5 a CSV file I suggest you use OpenCSV as it will 4 take care of escaped characters etc for 3 you.

Putting together the POI example from 2 here and the OpenCSV example from here gives you 1 this:

import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import au.com.bytecode.opencsv.CSVReader;

class Test {
    public static void main(String[] args) throws IOException {
        Workbook wb = new HSSFWorkbook();
        CreationHelper helper = wb.getCreationHelper();
        Sheet sheet = wb.createSheet("new sheet");

        CSVReader reader = new CSVReader(new FileReader("data.csv"));
        String[] line;
        int r = 0;
        while ((line = reader.readNext()) != null) {
            Row row = sheet.createRow((short) r++);

            for (int i = 0; i < line.length; i++)

        // Write the output to a file
        FileOutputStream fileOut = new FileOutputStream("workbook.xls");

enter image description here enter image description here

Score: 6

Apache POI is a library that can handle all kinds 4 of microsoft office documents, including 3 MS Excel. You can read the content of the 2 csv file with simple java code and use that 1 library to create and save a MS Excel document.

Score: 1

There are many check


you will get a lot 1 of alternative. Just google.

Score: 0

You may try Aspose.Cells for Java. You can use this component 3 to open a CSV file and save it as XLS file using Java. It also helps you work 2 with different Excel file versions.

Disclosure: I 1 work as developer evangelist at Aspose.

Score: 0

Using Groovy, I would do it this way:

// groovy to generate large csv file
def GROOVY_HOME = new File( System.getenv('GROOVY_HOME') )
if ( !GROOVY_HOME.canRead() ) {
  println( "Missing environment variable GROOVY_HOME: '${GROOVY_HOME}'" )

File file = new File("csv.csv")
if ( file.exists() ) {
    assert file.delete()
    assert file.createNewFile()

boolean append = true
FileWriter fileWriter = new FileWriter(file, append)
BufferedWriter buffWriter = new BufferedWriter(fileWriter)

buffWriter.write "sdiType=ReferenceValue,,,\n"
buffWriter.write "ListName,ListStartDate,Value,ValueStartDate\n"
println( "Writing to file 'csv.csv'" )

def y = 5000
while ( y-- > 0 ) {
    buffWriter.write "test" + y + ",1/1/2001,2008,1/1/2001\n"



More Related questions