【Java用法】使用poi写Java代码导出Excel文档的解决方案

简介: 【Java用法】使用poi写Java代码导出Excel文档的解决方案

【Java用法】使用EasyPoi导入与导出Excel文档的解决方案,这是另外一种方法导入导出文档

第一步:添加Maven依赖

<!--poi的依赖-->
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.10.1</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.10.1</version>
</dependency>

第二步:添加注解

下面是需要导出的实体类,需要添加@ExcelField注解;如果没有,请查看第二步中的一个注解类。

@ApiModel(value = "未提交日报实体")
@Data
public class DailyNoSubmitReport implements Serializable {
    @ApiModelProperty(value = "未提交日报id", example = "1")
    @ExcelField("编号")
    private Integer id;
    @ApiModelProperty(value = "手机号")
    @ExcelField("手机号")
    private String userName;
    @ApiModelProperty(value = "姓名")
    @ExcelField("姓名")
    private String trueName;
    @ApiModelProperty(value = "部门id")
    @ExcelField("部门id")
    private String deptId;
    @ApiModelProperty(value = "部门名称")
    @ExcelField("部门名称")
    private String deptName;
    @ExcelField(value = "未提交日期", dateFormat = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty(value = "未提交日期")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date noSubmitDate;
    @ExcelField("每周周几")
    @ApiModelProperty(value = "每周周几")
    private String dayOfWeek;
    @ExcelField(value = "创建日期", dateFormat = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty(value = "创建日期")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;
}

以下是注解类:

package com.iot.daily.annotation;
import java.lang.annotation.*;
/**
 * Description:ExcelField
 *
 * @author Jin
 * @create 2017-4-10
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelField {
    String value() default "";
    String dateFormat() default "";
    boolean isOnlyImport() default false;
    String isNullDefaultValue() default "N/A";
}

第三步:编写导出类

@Override
    public JsonResult exportExcel(User user, QueryParamDTO queryParamDTO) {
        if (user == null) {
            log.error("E|DailyStatisticsServiceImpl|exportExcel()|分页导出Excel日报未提交人员列表时,获取当前登录人失败!");
            return JsonResult.fail("获取当前登录人失败!");
        }
        int pageNum = queryParamDTO.getPageNum();
        int pageSize = queryParamDTO.getPageSize();
        try {
            PageInfo<Object> pageInfo = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() ->
                    dailyNoSubmitReportMapper.pageList(queryParamDTO));
            ExcelUtil.exports2007("日报未提交人员列表", pageInfo.getList());
            return JsonResult.ok("导出日报未提交人员列表成功!");
        } catch (Exception e) {
            log.error("E|DailyStatisticsServiceImpl|exportExcel()|分页导出Excel日报未提交人员列表失败!原因 = {}", e.getMessage());
        }
        return JsonResult.fail("分页导出Excel日报未提交人员列表时失败!");
    }

说明:上面导出类中的ExcelUtil工具类可以直接使用。即以下代码:

package com.iot.daily.common.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.uiotsoft.daily.account.exception.ApplicationException;
import com.uiotsoft.daily.account.exception.ErrorCode;
import com.uiotsoft.daily.annotation.ExcelField;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
/**
 * Description:
 *
 * @author Jin
 * @create 2017-07-27
 */
public class ExcelUtil {
    public static void exports(String sheetName, List<?> list) {
        if (CollUtil.isEmpty(list)) {
            throw new ApplicationException(ErrorCode.E_100106);
        }
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        try {
            ServletOutputStream out = response.getOutputStream();
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet(sheetName);
            for (int i = 0; i < list.size(); i++) {
                Object obj = list.get(i);
                Class clazz = obj.getClass();
                if (i == 0) {
                    HSSFRow row = sheet.createRow(i);
                    Field[] fields = clazz.getDeclaredFields();
                    int tmp = 0;
                    for (Field field : fields) {
                        HSSFCell cell = row.createCell(tmp);
                        ExcelField excelFiled = field.getAnnotation(ExcelField.class);
                        // 判断是否只支持导入
                        if (excelFiled == null || excelFiled.isOnlyImport()) {
                            continue;
                        }
                        cell.setCellValue(excelFiled.value());
                        tmp++;
                    }
                }
                HSSFRow row = sheet.createRow(i + 1);
                Field[] fields = clazz.getDeclaredFields();
                int tmp = 0;
                for (Field field : fields) {
                    ExcelField excelFiled = field.getAnnotation(ExcelField.class);
                    if (excelFiled == null || excelFiled.isOnlyImport()) {
                        continue;
                    }
                    HSSFCell cell = row.createCell(tmp);
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                    Method getMethod = pd.getReadMethod();
                    Object o = getMethod.invoke(obj);
                    if (!StrUtil.isBlank(excelFiled.dateFormat()) && o instanceof Date) {
                        cell.setCellValue(DateUtil.format((Date) o, excelFiled.dateFormat()));
                    } else {
                        cell.setCellValue(ObjectUtil.isNull(o) ? excelFiled.isNullDefaultValue() : String.valueOf(o));
                    }
                    tmp++;
                }
            }
            response.reset();
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("utf-8"), "ISO8859-1") + ".xls");
            response.setContentType("application/msexcel");
            wb.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApplicationException(ErrorCode.E_100106 + "导出excel失败,【" + e.getMessage() + "】");
        }
    }
    public static void exports2007(String sheetName, List<?> list) {
        if (CollUtil.isEmpty(list)) {
            throw new ApplicationException(ErrorCode.E_100106);
        }
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        try {
            ServletOutputStream out = response.getOutputStream();
            XSSFWorkbook wb = new XSSFWorkbook();
            XSSFSheet sheet = wb.createSheet(sheetName);
            for (int i = 0; i < list.size(); i++) {
                Object obj = list.get(i);
                Class clazz = obj.getClass();
                if (i == 0) {
                    XSSFRow row = sheet.createRow(i);
                    Field[] fields = clazz.getDeclaredFields();
                    int tmp = 0;
                    for (Field field : fields) {
                        XSSFCell cell = row.createCell(tmp);
                        ExcelField excelFiled = field.getAnnotation(ExcelField.class);
                        if (excelFiled == null || excelFiled.isOnlyImport()) {
                            continue;
                        }
                        cell.setCellValue(excelFiled.value());
                        tmp++;
                    }
                }
                XSSFRow row = sheet.createRow(i + 1);
                Field[] fields = clazz.getDeclaredFields();
                int tmp = 0;
                for (Field field : fields) {
                    ExcelField excelFiled = field.getAnnotation(ExcelField.class);
                    if (excelFiled == null || excelFiled.isOnlyImport()) {
                        continue;
                    }
                    XSSFCell cell = row.createCell(tmp);
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                    Method getMethod = pd.getReadMethod();
                    Object o = getMethod.invoke(obj);
                    if (!StrUtil.isBlank(excelFiled.dateFormat()) && o instanceof Date) {
                        cell.setCellValue(DateUtil.format((Date) o, excelFiled.dateFormat()));
                    } else {
                        cell.setCellValue(ObjectUtil.isNull(o) ? excelFiled.isNullDefaultValue() : String.valueOf(o));
                    }
                    tmp++;
                }
            }
            response.reset();
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("utf-8"), "ISO8859-1") + ".xlsx");
            response.setContentType("application/msexcel");
            wb.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出excel失败,[" + e.getMessage() + "]");
        }
    }
    public static <T> List<T> imports(FileInputStream is, Class<T> clazz) {
        List<T> result = Lists.newArrayList();
        try {
            HSSFWorkbook workbook = new HSSFWorkbook(is);
            Sheet sheet = workbook.getSheetAt(0);
            // 获取第0行标题
            Row row0 = sheet.getRow(0);
            // 遍历每一列
            for (int r = 1; r < sheet.getPhysicalNumberOfRows(); r++) {
                T obj = clazz.newInstance();
                Field[] fields = obj.getClass().getDeclaredFields();
                Row row = sheet.getRow(r);
                for (int c = 0; c < row.getPhysicalNumberOfCells(); c++) {
                    for (Field field : fields) {
                        ExcelField excelFiled = field.getAnnotation(ExcelField.class);
                        String title = getCellValue(row0.getCell(c).getCellType(), row0.getCell(c));
                        if (excelFiled == null && !title.equals(excelFiled.value())) {
                            continue;
                        }
                        String cellValue = getCellValue(row.getCell(c).getCellType(), row.getCell(c));
                        PropertyDescriptor pd = new PropertyDescriptor(field.getName(), obj.getClass());
                        if ("错误".equals(cellValue) || field.getType() == String.class) {
                            pd.getWriteMethod().invoke(obj, cellValue);
                            continue;
                        }
                        if (field.getType() == Integer.class) {
                            pd.getWriteMethod().invoke(obj, Integer.parseInt(cellValue));
                            continue;
                        }
                        if (field.getType() == Long.class) {
                            pd.getWriteMethod().invoke(obj, Long.parseLong(cellValue));
                            continue;
                        }
                        if (field.getType() == Float.class) {
                            pd.getWriteMethod().invoke(obj, Float.parseFloat(cellValue));
                            continue;
                        }
                        if (field.getType() == Double.class) {
                            pd.getWriteMethod().invoke(obj, Double.parseDouble(cellValue));
                            continue;
                        }
                        if (field.getType() == Date.class) {
                            pd.getWriteMethod().invoke(obj, DateUtil.parseDate(cellValue));
                        }
                    }
                }
                result.add(obj);
            }
        } catch (Exception e) {
            throw new RuntimeException("导如excel失败,[" + e.getMessage() + "]");
        }
        return result;
    }
    public static <T> List<T> imports2007(FileInputStream is, Class<T> clazz) {
        List<T> result = Lists.newArrayList();
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            Sheet sheet = workbook.getSheetAt(0);
            // 获取第0行标题
            Row row0 = sheet.getRow(0);
            // 遍历每一列
            for (int r = 1; r < sheet.getPhysicalNumberOfRows(); r++) {
                T obj = clazz.newInstance();
                Field[] fields = obj.getClass().getDeclaredFields();
                Row row = sheet.getRow(r);
                for (int c = 0; c < row.getPhysicalNumberOfCells(); c++) {
                    for (Field field : fields) {
                        ExcelField excelFiled = field.getAnnotation(ExcelField.class);
                        String title = getCellValue(row0.getCell(c).getCellType(), row0.getCell(c));
                        if (excelFiled == null || !title.equals(excelFiled.value())) {
                            continue;
                        }
                        String cellValue = getCellValue(row.getCell(c).getCellType(), row.getCell(c));
                        PropertyDescriptor pd = new PropertyDescriptor(field.getName(), obj.getClass());
                        if ("错误".equals(cellValue) || field.getType() == String.class) {
                            pd.getWriteMethod().invoke(obj, cellValue);
                            continue;
                        }
                        if (field.getType() == Integer.class) {
                            pd.getWriteMethod().invoke(obj, Integer.parseInt(cellValue));
                            continue;
                        }
                        if (field.getType() == Long.class) {
                            pd.getWriteMethod().invoke(obj, Long.parseLong(cellValue));
                            continue;
                        }
                        if (field.getType() == Float.class) {
                            pd.getWriteMethod().invoke(obj, Float.parseFloat(cellValue));
                            continue;
                        }
                        if (field.getType() == Double.class) {
                            pd.getWriteMethod().invoke(obj, Double.parseDouble(cellValue));
                            continue;
                        }
                        if (field.getType() == Date.class) {
                            pd.getWriteMethod().invoke(obj, DateUtil.parseDate(cellValue));
                        }
                    }
                }
                result.add(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导如excel失败,[" + e.getMessage() + "]");
        }
        return result;
    }
    public static String getCellValue(int cellType, Cell cell) {
        switch (cellType) {
            // 文本
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            // 数字、日期
            case Cell.CELL_TYPE_NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    // 日期型
                    return DateUtil.formatDate(cell.getDateCellValue());
                } else {
                    // 数字
                    return String.valueOf(cell.getNumericCellValue());
                }
                // 布尔型
            case Cell.CELL_TYPE_BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            // 空白
            case Cell.CELL_TYPE_BLANK:
                return cell.getStringCellValue();
            // 错误
            case Cell.CELL_TYPE_ERROR:
                return "错误";
            // 公式
            case Cell.CELL_TYPE_FORMULA:
                return "错误";
            default:
                return "错误";
        }
    }
    /*public static void main(String[] args) {
        File file = new File("E:\\123.xlsx");
        try {
            FileInputStream inputStream = new FileInputStream(file);
            List<TCmsContent> list = imports2007(inputStream, TCmsContent.class);
            System.out.println(list.get(0).getTitle());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }*/
}

完结!


相关文章
|
6月前
|
Python
Excel中如何批量重命名工作表与将每个工作表导出到单独Excel文件
本文介绍了如何在Excel中使用VBA批量重命名工作表、根据单元格内容修改颜色,以及将工作表导出为独立文件的方法。同时提供了Python实现导出工作表的代码示例,适用于自动化处理Excel文档。
|
Java API Apache
Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
【10月更文挑战第29天】Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
999 5
|
7月前
|
Java 测试技术 数据库
spring号码归属地批量查询,批量查询号码归属地,在线工具,可按省份城市运营商号段分类分开分别导出excel表格
简介:文章探讨Spring Boot项目启动优化策略,通过自定义监听器、异步初始化及分库分表加载优化等手段,将项目启动时间从280秒缩短至159秒,提升约50%,显著提高开发效率。
|
10月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
移动开发 前端开发 Java
Java最新图形化界面开发技术——JavaFx教程(含UI控件用法介绍、属性绑定、事件监听、FXML)
JavaFX是Java的下一代图形用户界面工具包。JavaFX是一组图形和媒体API,我们可以用它们来创建和部署富客户端应用程序。 JavaFX允许开发人员快速构建丰富的跨平台应用程序,允许开发人员在单个编程接口中组合图形,动画和UI控件。本文详细介绍了JavaFx的常见用法,相信读完本教程你一定有所收获!
12476 5
Java最新图形化界面开发技术——JavaFx教程(含UI控件用法介绍、属性绑定、事件监听、FXML)
|
JavaScript Java 测试技术
基于Java+SpringBoot+Vue实现的车辆充电桩系统设计与实现(系统源码+文档+部署讲解等)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
|
数据处理
Excel VBA 自动填充空白并合并相同值的解决方案
在Excel中,常需将一列数据中的空白单元格用上方最近的非空值填充,并合并连续相同值。本VBA宏方案自动完成此操作,包含代码实现、使用方法及注意事项。通过简单步骤添加宏,一键处理数据,提升效率,确保准确性。适用于频繁处理类似数据的用户。
514 7
|
数据格式 UED
记录一次NPOI库导出Excel遇到的小问题解决方案
【11月更文挑战第16天】本文记录了使用 NPOI 库导出 Excel 过程中遇到的三个主要问题及其解决方案:单元格数据格式错误、日期格式不正确以及合并单元格边框缺失。通过自定义单元格样式、设置数据格式和手动添加边框,有效解决了这些问题,提升了导出文件的质量和用户体验。
1024 3
|
前端开发
实现Excel文件和其他文件导出为压缩包,并导入
实现Excel文件和其他文件导出为压缩包,并导入
286 1
|
Java API Apache