如何从XLS(Excel)文件读取数据[Java,Android]

2022-09-02 13:35:37

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

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


答案 1

嗨,你只需要包含一个外部的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;
}

答案 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();
    }
}

推荐