Apache POI How To Convert CSV To Excel Using SuperCSV

Do you like this?

Summary:
This example shows you how to use Apache POI to create excel files with the content coming from CSV files. I will be using Maven to manage all the libraries' dependencies.


Content:

Following is the content of pom.xml for Maven:

<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>3.9</version>
</dependency>
<dependency>
	<groupId>net.sf.supercsv</groupId>
	<artifactId>super-csv</artifactId>
	<version>2.1.0</version>
</dependency>   
Following is the Java code to read data from a CSV file and then create a corresponding Excel file with different headers. Assume the CSV file contains the headers "Style No", "Barcode" and "Name". The generated Excel file contains "Product Code", "EAN Barcode" and "Name".
import java.io.*;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.supercsv.io.CsvMapReader;
import org.supercsv.io.ICsvMapReader;
import org.supercsv.prefs.CsvPreference;
public void generate() {
	String csvFilePath = "/path/to/csv/file.csv";
	Workbook wb = new HSSFWorkbook(); //You can use XSSFWorkbook to generate .xlsx files
	FileOutputStream fileOut;
	try {
		ICsvMapReader csvMapReader = new CsvMapReader(new FileReader(
				csvFilePath), CsvPreference.EXCEL_PREFERENCE);
		final String[] headers = csvMapReader.getHeader(true);
		Map csvRow;

		fileOut = new FileOutputStream("/path/to/excel/file.xls");
		Sheet sheet = wb.createSheet("products");

		int rowNo = 0;
		createExcelHeader(sheet, rowNo);

		while ((csvRow = csvMapReader.read(headers)) != null) {
			rowNo++;
			Row excelRow = sheet.createRow(rowNo);
			createExcelRow(csvRow, excelRow);
		}

		csvMapReader.close();
		wb.write(fileOut);
		fileOut.close();
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}

public void createExcelHeader(Sheet sheet, int rowNo) {
	Row excelRow = sheet.createRow(rowNo);
	excelRow.createCell(0).setCellValue("Product Code");
	excelRow.createCell(1).setCellValue("EAN Barcode");
	excelRow.createCell(2).setCellValue("Name");

}

public void createExcelRow(Map csvRow, Row excelRow) {
	excelRow.createCell(0).setCellValue(csvRow.get("Style No"));
	excelRow.createCell(1).setCellValue(csvRow.get("Barcode"));
	excelRow.createCell(2).setCellValue(csvRow.get("Name"));

}

 
comments powered by Disqus