Last active
November 20, 2021 21:59
-
-
Save timothyshort/c8c5b93f79823f921b66734891410f75 to your computer and use it in GitHub Desktop.
Read an Excel file and return a double array
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
// Dependencies: POI | HSSF Workbook/Sheet/Row/Cell | |
// This method will read and return Excel data into a double array | |
public static String[][] get(String filename) { | |
String[][] dataTable = null; | |
File file = new File(filename); | |
try { | |
// Create a file input stream to read Excel workbook and worksheet | |
FileInputStream xlfile = new FileInputStream(file); | |
HSSFWorkbook xlwb = new HSSFWorkbook(xlfile); | |
HSSFSheet xlSheet = xlwb.getSheetAt(0); | |
// Get the number of rows and columns | |
int numRows = xlSheet.getLastRowNum() + 1; | |
int numCols = xlSheet.getRow(0).getLastCellNum(); | |
// Create double array data table - rows x cols | |
// We will return this data table | |
dataTable = new String[numRows][numCols]; | |
// For each row, create a HSSFRow, then iterate through the "columns" | |
// For each "column" create an HSSFCell to grab the value at the specified cell (i,j) | |
for (int i = 0; i < numRows; i++) { | |
HSSFRow xlRow = xlSheet.getRow(i); | |
for (int j = 0; j < numCols; j++) { | |
HSSFCell xlCell = xlRow.getCell(j); | |
dataTable[i][j] = xlCell.toString(); | |
} | |
} | |
} catch (IOException e) { | |
System.out.println("ERROR FILE HANDLING " + e.toString()); | |
} | |
return dataTable; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment