Android 导入导出excel xls、xlsx

1.导入依赖

implementation group: 'org.apache.poi', name: 'poi-ooxml', version: '3.17'
implementation group: 'org.apache.xmlbeans', name: 'xmlbeans', version: '3.1.0'
implementation 'javax.xml.stream:stax-api:1.0'
implementation 'com.fasterxml:aalto-xml:1.2.2'

2.导出 xls   需要异步调用

    /**
     * 导出Excel
     *
     * @param listData
     * @return
     */
    public boolean exportExcel(List listData, String fileDir, String fileName) {
        if (TextUtils.isEmpty(fileDir) || TextUtils.isEmpty(fileName) || listData == null) {
            return false;
        }
        try {
            // 创建excel xlsx格式
            Workbook wb = new XSSFWorkbook();
            // 创建工作表
            Sheet sheet = wb.createSheet();
            String[] title = {"用户", "寄件人姓名", "寄件人手机号", "寄件人省/市/区", "寄件人详细地址", "收件人姓名", "收件人手机号", "收件人省/市/区", "收件人详细地址",
                    "实付款", "佣金", "创建时间"};
            //创建行对象
            Row row = sheet.createRow(0);
            // 设置有效数据的行数和列数
            int colNum = title.length;   // {"用户", "寄件人姓名", "寄件人手机号", "寄件人省/市/区", "寄件人详细地址", "收件人姓名", "收件人手机号", "收件人省/市/区", "收件人详细地址","实付款", "佣金","创建时间"}

            for (int i = 0; i < colNum; i++) {
                sheet.setColumnWidth(i, 20 * 256);  // 显示20个字符的宽度  列宽
                Cell cell1 = row.createCell(i);
                //第一行
                cell1.setCellValue(title[i]);
            }

            // 导入数据
            for (int rowNum = 0; rowNum < listData.size(); rowNum++) {

                // 之所以rowNum + 1 是因为要设置第二行单元格
                row = sheet.createRow(rowNum + 1);
                // 设置单元格显示宽度
                row.setHeightInPoints(28f);

                // PhonebillExpressBean 这个是我的业务类,这个是根据业务来进行填写数据
                PhonebillExpressBean bean = listData.get(rowNum);

                for (int j = 0; j < title.length; j++) {
                    Cell cell = row.createCell(j);

                    //要和title[]一一对应
                    switch (j) {
                        case 0:
                            //用户
                            cell.setCellValue(bean.getUserData());
                            break;
                        case 1:
                            //寄件人姓名
                            cell.setCellValue(bean.getSenderName());
                            break;
                        case 2:
                            //寄件人手机号
                            cell.setCellValue(bean.getSenderPhoneNumber());
                            break;
                        case 3:
                            //寄件人省/市/区
                            cell.setCellValue(bean.getSenderState());
                            break;
                        case 4:
                            //寄件人详细地址
                            cell.setCellValue(bean.getSenderDetailed());
                            break;
                        case 5:
                            //收件人姓名
                            cell.setCellValue(bean.getAddresseeName());
                            break;
                        case 6:
                            //收件人手机号
                            cell.setCellValue(bean.getAddresseePhone());
                            break;
                        case 7:
                            //收件人省/市/区
                            cell.setCellValue(bean.getAddresseeState());
                            break;
                        case 8:
                            //收件人详细地址
                            cell.setCellValue(bean.getAddresseeDetailed());
                            break;
                        case 9:
                            //实付款
                            cell.setCellValue(bean.getPrice() + "元");
                            break;
                        case 10:
                            //佣金
                            cell.setCellValue(bean.getCommission() + "元");
                            break;
                        case 11:
                            //创建时间
                            cell.setCellValue(bean.getCreatedAt());
                            break;
                    }
                }

            }

            String s = Environment.getExternalStorageDirectory() + "/" + fileDir;

            String mSDCardFolderPath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/" + fileDir;
            File dir = new File(s);
            //判断文件是否存在
            if (!dir.isFile()) {
                //不存在则创建
                dir.mkdir();
            }
//            File excel=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), convertTime(System.currentTimeMillis(),"MM月dd日HH时mm分")+".xlsx");
            File excel = new File(dir, convertTime(System.currentTimeMillis(), fileName) + ".xlsx");
            Log.e(" 导出路径", excel.getPath().toString());

            FileOutputStream fos = new FileOutputStream(excel);
            wb.write(fos);
            fos.flush();
            fos.close();
            return true;
        } catch (IOException e) {
            Log.e("ExpressExcle", "exportExcel", e);
            return false;

        }

    }


    //时间戳转换字符串
    public static String convertTime(long time, String patter) {
        SimpleDateFormat sdf = new SimpleDateFormat(patter);
        return sdf.format(new Date(time));
    }

3.导入  需要异步调用

/**
 * 导入excel
 *
 * @param fileName  本地文件路径
 */
private void readExcel(String fileName) {
    try {
        InputStream inputStream = new FileInputStream(fileName);
        Workbook workbook;
        if (fileName.endsWith(".xls")) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (fileName.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook(inputStream);
        } else {
            Log.d("!!!导入失败!!!", " 文件格式错误 ");
            return;
        }
        Sheet sheet = workbook.getSheetAt(0);//获取第一张表
        int rowsCount = sheet.getPhysicalNumberOfRows();//获取行数
        FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
        for (int r = 0; r < rowsCount; r++) {
            String str = "";
            Row row = sheet.getRow(r);//拿到行对象
            int physicalNumberOfCells = row.getPhysicalNumberOfCells();//获取该行总列数
            for (int i = 0; i < physicalNumberOfCells; i++) {
                CellValue v0 = formulaEvaluator.evaluate(row.getCell(i));//获取单元格对象
                str += v0.getStringValue();
            }
            Log.d("第" + (r + 1) + "行:", str);
        }
        workbook.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

4.注意:

需要读写权限


高版本动态申请权限

String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
int permission = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
if (permission != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, 1);
} else {
//logic
}

Android 10  有私密文件策略。解决:

res下新建xml文件夹,新建文件file_paths,文件内容如下


    
        
        

        

        

        
        
    

manifest  application 注册fileprovider


    

sdk 29以上 允许根目录新建文件

application 加上

android:requestLegacyExternalStorage="true"

你可能感兴趣的:(android,java,开发语言)