前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java导入导出excel

java导入导出excel

作者头像
liliane
发布2022-07-17 10:32:26
1.4K0
发布2022-07-17 10:32:26
举报
文章被收录于专栏:liliane随笔
代码语言:javascript
复制
/**
 * 导入excel
 * @param file 输入文件
 * @param clz 待转出格式
 * @param <T>
 * @return
 * @throws APIException
 */
public static <T> List<T> importExcel(File file, Class<T> clz) throws APIException {
    try {
        Workbook rwb = Workbook.getWorkbook(file);
        Sheet rs = rwb.getSheet(0);
        int cols = rs.getColumns();//列数
        int rows = rs.getRows();//行数
        logger.info("cols:{}, rows:{}", cols, rows);
        List<T> result = new ArrayList<T>();
        for (int i = 1; i < rows; i++) {//去掉第一行表头
            T item = clz.newInstance();
            Field[] fields = clz.getDeclaredFields();
            for (int j = 0; j < cols && j < fields.length; j++) {
                String cellContent = rs.getCell(j, i).getContents();
                Field field = fields[j];
                String methodName =
                        "set" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
                Method method = clz.getMethod(methodName, String.class);
                method.invoke(item, cellContent);
            }
            result.add(item);
        }
        logger.info("import result:{}", result);
        return result;
    } catch (Exception e) {
        if (e instanceof java.lang.ClassCastException) {
            throw new APIException(ResultEnum.APIEnum.PARAM_ERROR, "转出类型的所有字段必须支持String类型的set方法");
        }
        logger.error("importExcel clz:{}, error->", clz, e);
        throw new APIException(ResultEnum.APIEnum.SERVER_ERROR);
    }
}

/**
 * 导出数据到excel
 * @param sheetName
 * @param headers 表头,以英文逗号分隔
 * @param dataList 数据列表
 * @param targetPath 目标路径
 */
public static void exportExcel(String sheetName, String[] headers, List dataList, String targetPath) {
    try {
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }
        WritableWorkbook workbook = Workbook.createWorkbook(new File(targetPath));
        WritableSheet sheet = workbook.createSheet(sheetName, 1);

        Integer startRowIndex = 0;
        for (int i = 0; i < headers.length; i++) {
            Label label = new Label(i, startRowIndex, headers[i]);
            sheet.addCell(label);
        }

        //数据输出
        int listSize = dataList.size();

        if (listSize > 0) {
            Class clazz = dataList.get(0).getClass();
            Field[] fields = clazz.getDeclaredFields();
            for (int i = 0; i < listSize; i++) {
                int j = 0;
                for (Field field : fields) {
                    String feildName = field.getName();
                    String methodName = "get" + feildName.substring(0, 1).toUpperCase() + feildName.substring(1);
                    Method method = clazz.getMethod(methodName, new Class[] {});
                    Object fieldValue = method.invoke(dataList.get(i), new Object[] {});
                    String fieldValueStr = "";
                    if (fieldValue != null) {
                        fieldValueStr = fieldValue.toString();
                    }
                    Label label = new Label(j, i + 1, fieldValueStr);
                    sheet.addCell(label);
                    j++;
                }
            }
        }

        workbook.write();
        workbook.close();
    } catch (Exception e) {
        logger.error("export excel error->", e);
    }
}

代码语言:javascript
复制
常见问题:jxl.read.biff.BiffException: Unable to recognize OLE streamat jxl.read.biff.CompoundFile.<init>(CompoundFile.java:111)at jxl.read.biff.File.<init>(File.java:113)at jxl.Workbook.getWorkbook(Workbook.java:250)at jxl.Workbook.getWorkbook(Workbook.java:235)原因:jxl.Workbook.getWorkbook不支持.xlsx格式文件,需要转为.xls
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-02-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档