19

我搜索了stackoverflow,但没有找到明确的答案。如何从 XLS 文件的特定行和列中读取数据到我的 Android 应用程序?如何读取 XLS 文件?我不想将其转换为 CSV,因为我在尝试转换它们时遇到错误。

也许我可以使用这个http://www.andykhan.com/jexcelapi/tutorial.html#reading但我什至不知道如何将它导入到我的项目中。请帮忙。

4

2 回答 2

17

嗨,您只需要包含一个外部 jxl jar,您就可以完成相同的教程,这将帮助您了解读取 excel 文件的过程。为了您的参考,我粘贴了一些参考。读取第一张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;
}
于 2013-06-03T05:05:29.950 回答
1
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();
    }
}
于 2020-12-14T10:13:34.127 回答