天天看点

Android 读取excel (支持 xls和xlsx)

最近公司项目需要Android应用读取excel文件内容,所以就找了相关资料,找到两种读取excel文件的方法,下面为大家介绍:

一、jxl 读取excel文件

1.1、添加依赖:

implementation 'net.sourceforge.jexcelapi:jxl:2.6.12'
           

1.2、读取excel

public static void readExcel(Context context) {
      String logFilePath = Environment.getExternalStorageDirectory() + File.separator + "Visitor" ;
      File file=  new File(logFilePath,  "test.xls");
      Log.e("yy","file="+file.getAbsolutePath());
        try {
            InputStream is = new FileInputStream(file);
            Workbook book = Workbook.getWorkbook(is);
            book.getNumberOfSheets();
            Sheet sheet = book.getSheet(0);
            int Rows = sheet.getRows();

            for (int i = 1; i < Rows; ++i) {
                String name = (sheet.getCell(0, i)).getContents();
                String department = (sheet.getCell(1, i)).getContents();
                String company = (sheet.getCell(2, i)).getContents();
                String phone = (sheet.getCell(3, i)).getContents();

                Log.e("yy","第"+i+"行数据="+name+","+department+","+company+","+phone);

            }
            book.close();

        } catch (Exception e) {

            Log.e("yy",  "e"+e);
        }
    }
           

经过调试发现这种方式只支持97-2003(xls)版本,后来又经过多次尝试 发现下面代码可以支持2007以上版本(xlsx)

public static String readExcelxlsx() {
        String logFilePath = Environment.getExternalStorageDirectory() + File.separator + "Visitor";
        File file = new File(logFilePath, "test.xlsx");
        String str = "";
        String v = null;
        boolean flat = false;
        List<String> ls = new ArrayList<String>();
        try {
            ZipFile xlsxFile = new ZipFile(file);
            ZipEntry sharedStringXML = xlsxFile
                    .getEntry("xl/sharedStrings.xml");
            InputStream inputStream = xlsxFile.getInputStream(sharedStringXML);
            XmlPullParser xmlParser = Xml.newPullParser();
            xmlParser.setInput(inputStream, "utf-8");
            int evtType = xmlParser.getEventType();
            Log.e("=====>", "==xmlParser====>" + xmlParser.toString());
            while (evtType != XmlPullParser.END_DOCUMENT) {
                switch (evtType) {
                    case XmlPullParser.START_TAG:
                        String tag = xmlParser.getName();
                        if (tag.equalsIgnoreCase("t")) {
                            ls.add(xmlParser.nextText());
                            Log.e("=====>", "===xmlParser===>" + ls.toString());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                    default:
                        break;
                }
                evtType = xmlParser.next();
            }
            ZipEntry sheetXML = xlsxFile.getEntry("xl/worksheets/sheet1.xml");
            InputStream inputStreamsheet = xlsxFile.getInputStream(sheetXML);
            XmlPullParser xmlParsersheet = Xml.newPullParser();
            xmlParsersheet.setInput(inputStreamsheet, "utf-8");
            int evtTypesheet = xmlParsersheet.getEventType();
            while (evtTypesheet != XmlPullParser.END_DOCUMENT) {
                switch (evtTypesheet) {
                    case XmlPullParser.START_TAG:
                        String tag = xmlParsersheet.getName();
                        Log.e("=====>", "===tag222===>" + tag);
                        if (tag.equalsIgnoreCase("row")) {
                        } else if (tag.equalsIgnoreCase("c")) {
                            String t = xmlParsersheet.getAttributeValue(null, "t");
                            if (t != null) {
                                flat = true;
                                System.out.println(flat + "有");
                            } else {
                                System.out.println(flat + "没有");
                                flat = false;
                            }
                        } else if (tag.equalsIgnoreCase("v")) {
                            v = xmlParsersheet.nextText();
                            if (v != null) {
                                if (flat) {
                                    str += ls.get(Integer.parseInt(v)) + " ";
                                } else {
                                    str += v + " ";
                                }
                            }
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if (xmlParsersheet.getName().equalsIgnoreCase("row")
                                && v != null) {
                            str += "\n";
                        }
                        break;
                }
                evtTypesheet = xmlParsersheet.next();
            }
            System.out.println(str);
        } catch (ZipException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
        if (str == null) {
            str = "解析文件出现问题";
        }
        return str;

    }
           

1.3、经过上面的代码功能是解决了,但是上面这种数据是获取到了 但是对于后续的处理不是很友好,所以又去找了半天找到了poi读取的方法。

二、poi读取excel

2.1、添加依赖

网上各种说法添加的jar比较多,并且伴随各种 包冲突、65K等错误,最终 找到了一个外国小哥简化版的jar包

Android 读取excel (支持 xls和xlsx)

将上面两个jar 放进libs目录,build 即可,文末会有下载连接

2.2、读取excel

/**
     * 读取excel   (xls和xlsx)
     * @return
     */
    public static List<Map<String, String>> readExcel(String columns[]) {
        String logFilePath = Environment.getExternalStorageDirectory() + File.separator + "Visitor";
        File file = new File(logFilePath, "test.xls");
        String filePath=file.getAbsolutePath();
        Sheet sheet = null;
        Row row = null;
        Row rowHeader = null;
        List<Map<String, String>> list = null;
        String cellData = null;
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = null;
            }
            if (wb != null) {
                // 用来存放表中数据
                list = new ArrayList<Map<String, String>>();
                // 获取第一个sheet
                sheet = wb.getSheetAt(0);
                // 获取最大行数
                int rownum = sheet.getPhysicalNumberOfRows();
                // 获取第一行
                rowHeader = sheet.getRow(0);
                row = sheet.getRow(0);
                // 获取最大列数
                int colnum = row.getPhysicalNumberOfCells();
                for (int i = 1; i < rownum; i++) {
                    Map<String, String> map = new LinkedHashMap<String, String>();
                    row = sheet.getRow(i);
                    if (row != null) {
                        for (int j = 0; j < colnum; j++) {
                            if(columns[j].equals(getCellFormatValue(rowHeader.getCell(j)))){
                                cellData = (String) getCellFormatValue(row
                                        .getCell(j));
                                map.put(columns[j], cellData);
                                /*DecimalFormat df = new DecimalFormat("#");

                                System.out.println(    df.format(cellData));*/
                                Log.e("yy","cellData="+cellData);
                                Log.e("yy","map="+map);
                            }
                        }
                    } else {
                        break;
                    }
                    list.add(map);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**	获取单个单元格数据
     * @param cell
     * @return
     * @author lizixiang ,2018-05-08
     */
    public static Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {
            // 判断cell类型
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC: {
                    cellValue = String.valueOf(cell.getNumericCellValue());
                    break;
                }
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断cell是否为日期格式
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 转换为日期格式YYYY-mm-dd
                        cellValue = cell.getDateCellValue();
                    } else {
                        // 数字
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING: {
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }
           

2.3、调用

FileUtil.readExcel(new String[]{"姓名","部门","公司","电话"});
           

String数组里面对应我们的表头

如下:

Android 读取excel (支持 xls和xlsx)

5.0以上版本jar

4.0版本jar

最后特别说明: 本文是采用5.0以上版本jar,本代码是否适用于4.0版本jar并未做校验。。