Skip to content

Instantly share code, notes, and snippets.

@Faz95210
Last active May 29, 2018 05:59
Show Gist options
  • Save Faz95210/739023b29841eabb7a8a6b9052f7c9ac to your computer and use it in GitHub Desktop.
Save Faz95210/739023b29841eabb7a8a6b9052f7c9ac to your computer and use it in GitHub Desktop.
[Parse xlsx from java] Parse xlsx excel file from java with apache poi #Java #Excel #Xlsx #Apache #POI
import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
/*
** Gradle Import :
* compile group: 'org.apache.poi', name: 'poi', version: '3.17'
* compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.17'
*/
private static Workbook openExcel() {
// Opening excel as workbook
try {
final Workbook workbook = StreamingReader.builder()
.rowCacheSize(10) // number of rows to keep in memory (defaults to 10)
.bufferSize(1024) // buffer size to use when reading InputStream to file (defaults to 1024)
.open(Files.newInputStream(Paths.get(excelPath)));
return workbook;
} catch (IOException | NotOfficeXmlFileException ex) {
return null;
}
}
private static void parseExcel(final int sheetNumber) {
for (final Row r : workbook.getSheetAt(sheetNumber)) { // Iterates over each line of the sheet. You can also get a sheet by its name rather than its number
final Cell cell = r.getCell(X); // get the cell at column X;
// Query values
cell.getStringCellValue(); // get String Value
cell.getNumericCellValue(); // get Numeric value (float)
cell.getColumnIndex(); // get Column index
cell.getRow() // get Row number
// Set values
cell.setCellValue("value"); // Edit value in cell
}
}
public void main(String[] args) {
final Workbook workbook = openExcel("Path/to/your/excel.xlsx");
parseSheets(0) // parse first sheets.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment