读取Excel获得内容利用jsoup解析html判断并创建新的Excel写入结果

1、首先要申请权限

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS_STORAGE, 130);
                    } else {
                        intentSelect();
                    }
                } else {
                    intentSelect();
                }
}
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && data != null) {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                LogUtils.d("uri=" + uri);
                if (uri != null) {
                    String path = uri.getPath();
                    if (path.contains("storage/")) {
                        path = path.substring(path.indexOf("storage/"));
                    }
                    File file1 = new File(path);
                    LogUtils.d("file1=" + file1 + ",exists=" + file1.exists());
                    String pathCopy=path.substring(0,path.indexOf(file1.getName()));
                    excelUtils.setPathCopy(pathCopy);

                    if (excelUtils.checkIfExcelFile(file1) && file1.exists()) {
                        try {
                            excelUtils.readExcel(file1);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    } else {
                        ToastUtils.showText("不是Excel文件或文件路径不对,重新保存到本地");
                    }
                }
            }
        }
    }

2、打开文件管理器选择Excel文件

private void intentSelect() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//设置类型,我这里是任意类型,任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 1);
    }

3、写ExcelUtils工具类

/**
 * @description: Excel 工具类
 */
public class ExcelUtils {

    private List list = new ArrayList<>();

    public static ExcelUtils create() {
        return new ExcelUtils();
    }

    private FileOutputStream out;
    private FileInputStream input;
    private int rowsCount = 0;
    private String pathCopy;

    public void setPathCopy(String pathCopy) {
        this.pathCopy = pathCopy;
    }

    /**
     * 读取Excel文件
     *
     * @param file
     * @throws FileNotFoundException
     */
    public void readExcel(File file) throws FileNotFoundException {
        if (file == null && file.length() == 0) {
            LogUtils.d("读取Excel出错,文件为空文件");
            return;
        }
        input = new FileInputStream(file);
        try {
            Workbook workbook = create(input);
            Sheet sheet = workbook.getSheetAt(0);
            rowsCount = sheet.getPhysicalNumberOfRows();
            FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
            for (int r = 0; r < rowsCount; r++) {
                Row row = sheet.getRow(r);
                int cellsCount = row.getPhysicalNumberOfCells();
                ExcelEntity entity = new ExcelEntity();
                //每次读取一行的内容
                for (int c = 0; c < cellsCount; c++) {
                    //将每一格子的内容转换为字符串形式
                    String value = getCellAsString(row, c, formulaEvaluator);
                    if (TextUtils.isEmpty(value)) {
                        value = "";
                    }
                    String cellInfo = "r:" + r + "; c:" + c + "; v:" + value;
                    LogUtils.d(cellInfo);
                    entity.setRow(r);
                    switch (c) {
                        case 0:
                            entity.setCompanyName(value);
                            break;
                        case 1:
                            entity.setName(value);
                            break;
                        case 2:
                            entity.setDeposit(value);
                            break;
                        case 3:
                            entity.setMoney(value);
                            break;
                        case 4:
                            entity.setIsOffShelf(value);
                            break;
                        case 5:
                            entity.setIsCloseStore(value);
                            break;
                    }
                }
                list.add(entity);
            }
        } catch (Exception e) {
            /* proper exception handling to be here */
            LogUtils.e("error===" + e.toString());
        } finally {
            IGlobalCallback callback = CallbackManager.getInstance().getCallback("html");
            if (callback != null) {
                Map map = new HashMap<>();
                map.put("size", rowsCount);
                map.put("list", list);
                callback.executeCallback(map);
            }
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Workbook create(InputStream in) throws
            IOException, InvalidFormatException {
        if (!in.markSupported()) {
            in = new PushbackInputStream(in, 8);
        }
        if (POIFSFileSystem.hasPOIFSHeader(in)) {
            return new HSSFWorkbook(in);
        }
        if (POIXMLDocument.hasOOXMLHeader(in)) {
            return new XSSFWorkbook(OPCPackage.open(in));
        }
        throw new IllegalArgumentException("你的excel版本目前poi解析不了");
    }

    /**
     * 读取excel文件中每一行的内容
     *
     * @param row
     * @param c
     * @param formulaEvaluator
     * @return
     */
    private String getCellAsString(Row row, int c, FormulaEvaluator formulaEvaluator) {
        String value = "";
        try {
            Cell cell = row.getCell(c);
            CellValue cellValue = formulaEvaluator.evaluate(cell);
            if (cellValue != null) {
                switch (cellValue.getCellType()) {
                    case Cell.CELL_TYPE_BOOLEAN:
                        value = "" + cellValue.getBooleanValue();
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        double numericValue = cellValue.getNumberValue();
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            double date = cellValue.getNumberValue();
                            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
                            value = formatter.format(HSSFDateUtil.getJavaDate(date));
                        } else {
                            value = "" + numericValue;
                        }
                        break;
                    case Cell.CELL_TYPE_STRING:
                        value = "" + cellValue.getStringValue();
                        break;
                    default:
                        break;
                }
            }
        } catch (NullPointerException e) {
            /* proper error handling should be here */
            LogUtils.e(e.toString());
        }
        return value;
    }

    /**
     * 写入excel
     *
     * @param
     */
    public void writeExcel(List list, ProgressDialog dialog,int type) {
//        File file = new File("storage/emulated/0/Download/WeiXin/店铺数量Copy.xlsx");
        try {
            File file;
            Workbook workbook;
            if (type == 1) {//2003
                file= new File(pathCopy+"店铺数量2003版.xls");
                workbook = new HSSFWorkbook(); // 定义一个新的工作簿
            }else {//2007
                file = new File(pathCopy+"店铺数量2007版.xlsx");
                workbook = new XSSFWorkbook(); // 定义一个新的工作簿
            }
            Sheet sheet = workbook.createSheet("sheet0");  // 创建第一个Sheet页
            for (ExcelEntityListBean bean : list) {
                int index = list.indexOf(bean);
                int size = list.size() - 1;
                dialog.setData("写入excel中...", index + "/" + size, index * 100 / size);
                LogUtils.d("写入excel中..."+index + "/" + size);
                Row row = sheet.createRow(bean.getR()); // 创建一个行
                row.createCell(0).setCellValue(bean.getEntity().getCompanyName()); // 创建一个单元格  第1列
                row.createCell(1).setCellValue(bean.getEntity().getName()); // 创建一个单元格  第1列
                row.createCell(2).setCellValue(bean.getEntity().getDeposit()); // 创建一个单元格  第1列
                row.createCell(3).setCellValue(bean.getEntity().getMoney()); // 创建一个单元格  第1列
                row.createCell(4).setCellValue(bean.getEntity().getIsOffShelf()); // 创建一个单元格  第1列
                row.createCell(5).setCellValue(bean.getEntity().getIsCloseStore()); // 创建一个单元格  第1列
                out = new FileOutputStream(file);
                workbook.write(out);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            dialog.setData("写入成功!",list.size()+"/"+list.size(),100);
            LogUtils.d("写入成功!");
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据类型后缀名简单判断是否Excel文件
     *
     * @param file 文件
     * @return 是否Excel文件
     */
    public boolean checkIfExcelFile(File file) {
        if (file == null) {
            return false;
        }
        String name = file.getName();
        //”.“ 需要转义字符
        String[] list = name.split("\\.");
        //划分后的小于2个元素说明不可获取类型名
        if (list.length < 2) {
            return false;
        }
        String typeName = list[list.length - 1];
        //满足xls或者xlsx才可以
        return "xls".equals(typeName) || "xlsx".equals(typeName);
    }
}

4、通过jsoup解析网站链接

private void getDataByJsoup(final String h5Url){
	//线程池,支持定时的以及周期性的任务执行,规定最多只有100个
	ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(100);
	scheduledThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 网络加载HTML文档
                    Document doc = Jsoup.connect(h5Url)
                            .timeout(0) // 设置超时时间
                            .maxBodySize(0)//避免由于html内容太多,导致只解析出来一部分。不设定内容的长度
                            .get(); // 使用GET方法访问URL
                     //通过html中的classId来查找对应的内容
                    Elements elements=doc.getElementsByClass("notic_box");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
}

你可能感兴趣的:(android工具,java)