Skip to content

Instantly share code, notes, and snippets.

@sinarf
Forked from tranminhan/ExcelReading.java
Last active August 29, 2015 14:01
Show Gist options
  • Save sinarf/efa6ef2fdbb5f2a6fd64 to your computer and use it in GitHub Desktop.
Save sinarf/efa6ef2fdbb5f2a6fd64 to your computer and use it in GitHub Desktop.
/*
* Dependencies: Apache POI Library from http://poi.apache.org/
*/
package poi_excels;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
/**
*
* @author Munawwar
*/
public class ExcelReading {
public static void echoAsCSV(Sheet sheet) {
Row row = null;
for (int i = 0; i < sheet.getLastRowNum() + 1 ; i++) {
row = sheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++) {
System.out.print("\"" + row.getCell(j) + "\";");
}
System.out.println();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
InputStream inp = null;
try {
inp = new FileInputStream("myxlsx/sample.xlsx");
Workbook wb = WorkbookFactory.create(inp);
for(int i=0;i<wb.getNumberOfSheets();i++) {
System.out.println(wb.getSheetAt(i).getSheetName());
echoAsCSV(wb.getSheetAt(i));
}
} catch (InvalidFormatException ex) {
Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
inp.close();
} catch (IOException ex) {
Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
@sinarf
Copy link
Author

sinarf commented May 9, 2014

Read an convert an Excel file to CSV.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment