Tuesday, 24 July 2012

Convert CSV file to Excel File

Convert CSV file to Excel File 

Add this poi-2.5.1.jar to class path



import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import java.io.*;

public class ExcelConverter {
public static void main(String args[]) throws IOException {
ArrayList arList = null;
ArrayList al = null;
String fName = "c:\\hai.csv";
String thisLine;
int count = 0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i = 0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null) {
al = new ArrayList();
String strar[] = thisLine.split(",");
for (int j = 0; j < strar.length; j++) {
al.add(strar[j]);
}
arList.add(al);
System.out.println();
i++;
}

try {
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for (int k = 0; k < arList.size(); k++) {
ArrayList ardata = (ArrayList) arList.get(k);
System.out.println("ardata " + ardata.size());
HSSFRow row = sheet.createRow((short) 0 + k);
for (int p = 0; p < ardata.size(); p++) {
System.out.print("  data is "+ ardata.get(p));
HSSFCell cell = row.createCell((short) p);
cell.setCellValue(ardata.get(p).toString());
}
System.out.println("  control reached aa");
FileOutputStream fileOut = new FileOutputStream(
"C:\\excel\\xfile.xls");
System.out.println("file output stream");
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated");
}
} catch (Exception ex) {
} // main method ends
}
}

No comments:

Post a Comment

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...