java基于注解excel的导入与导出

1 maven坐标

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10-FINAL</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.10-FINAL</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.6</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>

2 创建注解

/**
 * @author xujj
 * @version 1.0.0
 * @ClassName ExcelField.java
 * @Description TODO
 * @createTime 2021年07月31日 11:15:00
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD })
public @interface ExcelField {
    /**
     * Excel中的列名
     *
     * @return
     */
    public abstract String name();

    /**
     * 列名对应的A,B,C,D...,不指定按照默认顺序排序
     *
     * @return
     */
    public abstract String column() default "";

    /**
     * 提示信息
     *
     * @return
     */
    public abstract String prompt() default "";

    /**
     * 设置只能选择不能输入的列内容
     *
     * @return
     */
    public abstract String[] combo() default {};

    /**
     * 是否导出数据
     *
     * @return
     */
    public abstract boolean isExport() default true;

    /**
     * 是否为重要字段(整列标红,着重显示)
     *
     * @return
     */
    public abstract boolean isMark() default false;

    /**
     * 是否合计当前列
     *
     * @return
     */
    public abstract boolean isSum() default false;

    /**
     * 序号 对应excel字段的位置
     * @return
     */
    public abstract int index();

}

3 创建实体类,在属性中添加刚才创建的注解

public class Apply {

    private Long id;
    private String accessToken;
    private String itemCode;
    private String taskHandleItem;
    private String applyNo;
    private String itemName;
    private String targetType;
    @ExcelField(name = "办理对象名称",index = 11)
    private String targetName;
    @ExcelField(name = "办理对象编号",index = 13)
    private String targetNo;
    @ExcelField(name = "申请人姓名",index = 11)
    private String username;
    private String licenseType;
    @ExcelField(name = "申请人证件编号",index = 13)
    private String licenseNo;
    @ExcelField(name = "申请人手机号",index = 10)
    private String mobile;
    @ExcelField(name = "受理部门(办理点)编号",index = 7)
    private String departCode;
    @ExcelField(name = "受理部门(办理点)名称",index = 8)
    private String departName;
    private String source;
    private String content;
    @ExcelField(name = "保存时间",index = 5)
    private String opTime;
    private String districtCode;

    private Info info;

    private String ProjectType;
    private String isStatistics;

    @ExcelField(name = "对应订单号",index = 3)
    private String orderNo;//对应订单号
    @ExcelField(name = "订购端来源",index = 6)
    private String platform;
    @ExcelField(name = "票类型",index = 8)
    private String scheduleName;
    @ExcelField(name = "reservedate",index = 9)
    private String reservedate;
    @ExcelField(name = "票面价格",index = 15)
    private String showPrice;
    @ExcelField(name = "groupName",index = 1)
    private String groupName;
    @ExcelField(name = "voucherNo",index = 2)
    private String voucherNo;
    ...

4 读取excel文件

    @Test
    public void testReadExcel() throws InstantiationException, IllegalAccessException {
        List<Apply> applyList = importExcelUtil.readFromExcel(Constant.filePath, Apply.class);
        System.out.println(applyList);
    }

5 写入excel

@RequestMapping("export")
    public void export(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1、查询要导出的数据
        List<Apply> applyList = applyService.findAll();
        //2、把数据填充到excel里
        //获取excel导出模板
        ExportExcelUtil excelUtil = new ExportExcelUtil();
        //模板文件所在文章
        ClassPathResource classPathResource = new ClassPathResource("static/excleTemplate/test.xlsx");
        File excelTplFile = classPathResource.getFile();
        //工作簿
        Workbook workbook = excelUtil.getWorkbook(excelTplFile);
        //sheet  部门信息为sheet名称
        Sheet sheet = excelUtil.getSheet(workbook,"sheet1");
        for (int i = 0; i < applyList.size(); i++) {
            Apply apply =  applyList.get(i);
            //行
            Row row = excelUtil.createRow(sheet);
            Cell cell0 = excelUtil.createCell(row,0);
            cell0.setCellValue(apply.getApplyNo());

            Cell cell1 = excelUtil.createCell(row,1);
            cell1.setCellValue(apply.getContent());

            Cell cell2 = excelUtil.createCell(row,2);
            cell2.setCellValue(apply.getDepartCode());

            Cell cell3 = excelUtil.createCell(row,3);
            cell3.setCellValue(apply.getDepartName());
        }

        //把写好的excel发送到客户端
        String fileName="dept_list.xlsx";
        response.setContentType("application/ms-excel");
        response.setHeader("Content-disposition", "attachment;filename="+fileName);
        ServletOutputStream ouputStream = response.getOutputStream();
        workbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    } 

6 相关工具类

import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileInputStream;
/**
 * @author xujj
 * @version 1.0.0
 * @ClassName ExportExcelUtil.java
 * @Description TODO
 * @createTime 2021年07月29日 16:42:00
 */
public class ExportExcelUtil {
    private CellStyle cs;
    /**
     * 描述:根据文件路径获取项目中的文件
     *
     * @param path 文件路径
     * @param filePath
     * @return
     * @throws Exception
     */
    public File getExcelTplFile(String path, String filePath) throws Exception {
        String classDir = null;
        String fileBaseDir = null;
        File file = null;
		/*classDir = Thread.currentThread().getContextClassLoader()
				.getResource("").getPath();
		System.out.println(classDir);
		fileBaseDir = classDir.substring(1, classDir.lastIndexOf("classes")).replaceAll("%20", " ");*/
        file = new File(path+filePath);
        if (!file.exists()) {
            throw new Exception("模板文件不存在!");
        }
        return file;
    }
    /**
     * 创建工作簿
     * @param file
     * @return
     * @throws Exception
     */
    public Workbook getWorkbook(File file) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        Workbook wb = new ImportExcelUtil().getWorkbook(fis, file.getName()); // 获取工作薄
        return wb;
    }

    /**
     * 创建Sheet
     * @param wb
     * @param sheetName
     * @return
     * @throws Exception
     */
    public Sheet getSheet(Workbook wb, String sheetName) throws Exception {
        cs = setSimpleCellStyle(wb); // Excel单元格样式
        Sheet sheet = wb.getSheet(sheetName);
        return sheet;
    }

    /**
     * 创建Row
     * @param sheet
     * @return
     * @throws Exception
     */
    public Row createRow(Sheet sheet) throws Exception {
        // 循环插入数据
        int lastRow = sheet.getLastRowNum() + 1; // 插入数据的数据ROW
        Row row = sheet.createRow(lastRow);
        return row;
    }
    /**
     * 创建Cell
     * @param row
     * @param CellNum
     * @return
     * @throws Exception
     */
    public Cell createCell(Row row, int CellNum) throws Exception {
        Cell cell = row.createCell(CellNum);
        cell.setCellStyle(cs);
        return cell;
    }

    /**
     * 描述:设置简单的Cell样式
     *
     * @return
     */
    public CellStyle setSimpleCellStyle(Workbook wb) {
        CellStyle cs = wb.createCellStyle();

        cs.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
        cs.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
        cs.setBorderTop(CellStyle.BORDER_THIN);// 上边框
        cs.setBorderRight(CellStyle.BORDER_THIN);// 右边框

        cs.setAlignment(CellStyle.ALIGN_CENTER); // 居中

        return cs;
    }

}
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

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.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

/**
 * @author xujj
 * @version 1.0.0
 * @ClassName ImportExcelUtil.java
 * @Description TODO
 * @createTime 2021年07月29日 16:43:00
 */
@Component
public class ImportExcelUtil {

    private final static String excel2003L =".xls";    //2003- 版本的excel
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel

    /**
     * 描述:获取IO流中的数据,组装成List<List<Object>>对象
     * @param in,fileName
     * @return
     * @throws IOException
     */
    public  List<List<Object>> getListByExcel(InputStream in,String fileName) throws Exception{
        List<List<Object>> list = null;

        //创建Excel工作薄
        Workbook work = this.getWorkbook(in,fileName);
        if(null == work){
            throw new Exception("创建Excel工作薄为空!");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if(sheet==null){continue;}

            //遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum()+1; j++) {
                row = sheet.getRow(j);
                if(row==null||row.getFirstCellNum()==j){continue;}

                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                boolean ok = true;
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    if (cell == null){
                        ok = false;
                        break;
                    }
                    li.add(this.getCellValue(cell));
                }
                if (ok){
                    list.add(li);
                }

            }
        }
        return list;
    }
    /**
     * 描述:根据文件后缀,自适应上传文件的版本
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if(excel2003L.equals(fileType)){
            wb = new HSSFWorkbook(inStr);  //2003-
        }else if(excel2007U.equals(fileType)){
            wb = new XSSFWorkbook(inStr);  //2007+
        }else{
            throw new Exception("解析的文件格式有误!");
        }
        return wb;
    }

    /**
     * 描述:对表格中数值进行格式化
     * @param cell
     * @return
     */
    public  Object getCellValue(Cell cell){
        Object value = null;
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if("General".equals(cell.getCellStyle().getDataFormatString())){
                    value = df.format(cell.getNumericCellValue());
                }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
                    value = sdf.format(cell.getDateCellValue());
                }else{
                    value = df2.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            default:
                break;
        }
        return value;
    }
    public <T> List<T> readFromExcel(String filePath,Class<T> tClass) throws IllegalAccessException,
            InstantiationException {
        String fileName = filePath.substring(filePath.lastIndexOf("\\"));
        File file = new File(filePath);
        log.info("文件地址:"+filePath);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.info("");
        }
        List<List<Object>> listByExcel = null;
        try {
            listByExcel = this.getListByExcel(inputStream, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<T> applyList = new ArrayList<>();
        for (List<Object> objects : listByExcel) {
            Field[] fields = ReflectUtil.getFields(Apply.class);
            T t = tClass.newInstance();
            for (Field field : fields) {
                if (AnnotationUtil.hasAnnotation(field, ExcelField.class)) {
                    Object index = AnnotationUtil.getAnnotationValue(field, ExcelField.class, "index");
                    ReflectUtil.setFieldValue(t, field, objects.get(Convert.toInt(index)));
                }
            }
            applyList.add(t);
        }
        log.info("------------------------------end-------------------------------");
        return applyList;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值