How to read data from XLS (Excel) file [Java, Android]
I have searched stackoverflow but I didn't find a clear answer. How can I read data from particular rows and columns of XLS file to my Android application? How can I read XLS file? I don't want to convert it to CSV because I get errors when I try to convert them.
Maybe I could use this http://www.andykhan.com/jexcelapi/tutorial.html#reading but I even don't know how could I import it into my project. Please help.
Solution 1:
Hi you just need to include an external jxl jar and you can go through the same tutorial which will help you understand the process of reading excel files.. for your referance i am pasting some ref. code which reads very first sheet of excel and creates a resultset.
public List<String> read(String key) throws IOException {
List<String> resultSet = new ArrayList<String>();
File inputWorkbook = new File(inputFile);
if(inputWorkbook.exists()){
Workbook w;
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over column and lines
for (int j = 0; j < sheet.getRows(); j++) {
Cell cell = sheet.getCell(0, j);
if(cell.getContents().equalsIgnoreCase(key)){
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cel = sheet.getCell(i, j);
resultSet.add(cel.getContents());
}
}
continue;
}
} catch (BiffException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
resultSet.add("File not found..!");
}
if(resultSet.size()==0){
resultSet.add("Data not found..!");
}
return resultSet;
}
Solution 2:
private void printlnToUser(Cell str) {
final Cell string = str;
if (output.length() > 8000) {
CharSequence fullOutput = output.getText();
fullOutput = fullOutput.subSequence(5000, fullOutput.length());
output.setText(fullOutput);
}
output.append(string + "\n");
}
public void ReadXLSX(File path) {
try {
FileInputStream fis = new FileInputStream(path);
XSSFWorkbook myWorkBook = new XSSFWorkbook(fis);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
break;
case Cell.CELL_TYPE_NUMERIC:
break;
case Cell.CELL_TYPE_BOOLEAN:
break;
default:
}
printlnToUser(cell);
}
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}