Created
April 19, 2014 01:03
-
-
Save robertchong/11070244 to your computer and use it in GitHub Desktop.
Convert Delimited text or .csv to Excel using Apache POI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.hi.hiqww.jfxclient.export; | |
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; | |
/** | |
* Delimited text or .csv to Excel using Apache POI | |
* See http://codeyard.wordpress.com/2011/05/23/delimited-text-or-csv-to-excel-using-apache-poi/ | |
*/ | |
public class DelimitedToXls { | |
@SuppressWarnings("deprecation") | |
public static void main(String args[]) throws IOException { | |
ArrayList<ArrayList<String>> allRowAndColData = null; | |
ArrayList<String> oneRowData = null; | |
String fName = "C:\\input.csv"; | |
String currentLine; | |
FileInputStream fis = new FileInputStream(fName); | |
DataInputStream myInput = new DataInputStream(fis); | |
int i = 0; | |
allRowAndColData = new ArrayList<ArrayList<String>>(); | |
while ((currentLine = myInput.readLine()) != null) { | |
oneRowData = new ArrayList<String>(); | |
String oneRowArray[] = currentLine.split(";"); | |
for (int j = 0; j < oneRowArray.length; j++) { | |
oneRowData.add(oneRowArray[j]); | |
} | |
allRowAndColData.add(oneRowData); | |
System.out.println(); | |
i++; | |
} | |
try { | |
HSSFWorkbook workBook = new HSSFWorkbook(); | |
HSSFSheet sheet = workBook.createSheet("sheet1"); | |
for (int i = 0; i < allRowAndColData.size(); i++) { | |
ArrayList<?> ardata = (ArrayList<?>) allRowAndColData.get(i); | |
HSSFRow row = sheet.createRow((short) 0 + i); | |
for (int k = 0; k < ardata.size(); k++) { | |
System.out.print(ardata.get(k)); | |
HSSFCell cell = row.createCell((short) k); | |
cell.setCellValue(ardata.get(k).toString()); | |
} | |
System.out.println(); | |
} | |
FileOutputStream fileOutputStream = new FileOutputStream("C:\\outputFile.xls"); | |
workBook.write(fileOutputStream); | |
fileOutputStream.close(); | |
} catch (Exception ex) { | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment