Java code for convert xlsx or xls file to csv file

static void excelTocsvConvert(File inputFile, File outputFile) {
// For storing data into CSV files
StringBuffer data = new StringBuffer();
try {
FileOutputStream fos = new FileOutputStream(outputFile);

// Get the workbook object for XLSX file
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(inputFile));

// Get first sheet from the workbook
XSSFSheet sheet = wBook.getSheetAt(0);
Row row;
Cell cell;

// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
row = rowIterator.next();

// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {

cell = cellIterator.next();

switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
data.append(cell.getBooleanCellValue() + “,”);

break;
case Cell.CELL_TYPE_NUMERIC:
data.append(cell.getNumericCellValue() + “,”);

break;
case Cell.CELL_TYPE_STRING:
data.append(cell.getStringCellValue() + “,”);
break;

case Cell.CELL_TYPE_BLANK:
data.append(“” + “,”);
break;
default:
data.append(cell + “,”);

}
}
data.append(‘\n’);
}

fos.write(data.toString().getBytes());
fos.close();

} catch (Exception ioe) {
ioe.printStackTrace();
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s