我搜索了stackoverflow,但我找不到明确的答案。如何从XLS文件的特定行和列中读取数据到我的Android应用程序?我怎样才能读取XLS文件?我不想将其转换为CSV,因为我在尝试转换它时遇到错误。
也许我可以使用这个http://www.andykhan.com/jexcelapi/tutorial.html#reading,但我甚至不知道如何将其导入我的项目中。请帮忙。
答案 0 :(得分:16)
您好,您只需要包含一个外部jxl jar,您可以通过相同的教程,这将有助于您了解阅读excel文件的过程..为了您的referance我粘贴一些参考。代码,它读取第一张excel表并创建结果集。
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;
}
答案 1 :(得分:0)
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();
}
}