java springboot注解通用导入导出Excel

springboot 通用的导入和导出 代码简单方便

1.先写个 ExcelResources 类 

package com.pengtu.utils.ExcelUtils;

import java.lang.annotation.*;

@Target({ElementType.FIELD})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelResources {
	
	int order() default 9999;//定义字段在excel的单元格列坐标位置

	String title() default "";//定义列坐标对应的标题

	int cloumn() default 100;//定义列宽

	String pattern() default "";//定义日期显示格式

}

2.再写个导出的util

package com.pengtu.service.util;


import com.pengtu.Constants;
import com.pengtu.dao.govinvested.ProjectDao;
import com.pengtu.entity.govinvested.Project;
import com.pengtu.service.govinvested.ProjectService;
import com.pengtu.utils.ExcelUtils.ExcelResources;
import com.pengtu.utils.ExcelUtils.SexType;
import com.pengtu.utils.ExcelUtils.TitleAndCloumn;
import com.pengtu.utils.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;

import javax.persistence.Column;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import org.springframework.stereotype.Service;

@Service
public class ExcelService {

    private static float title_row_height=30;//标题行高
    private static float data_row_height=25;//数据行高

	public void exportExcel(HttpServletRequest request, HttpServletResponse response, String fileName , List<?> excelDatas, Class<?> clz ) {
	
        try {

            HSSFWorkbook resultWb=new HSSFWorkbook();
            HSSFSheet sheet=resultWb.createSheet();//创建sheet

			//根据类类型信息获取导出的excel对应的标题和列宽  key-列号,value-标题和列宽
            HashMap<Integer, TitleAndCloumn> orderTitleAndCloumnMap=getTitleAndCloumnMap(clz);

            //设置列宽
            orderTitleAndCloumnMap.forEach((k,v) -> {
                sheet.setColumnWidth(k, v.getCloumn()*256);
            });

            HSSFRow row0=sheet.createRow(0);
            //设置标题行高
            row0.setHeightInPoints(title_row_height);

			//创建标题单元格格式
            HSSFCellStyle titleCellStyle=getCellStyle(resultWb,11,true,IndexedColors.BLACK.index);
            //填充标题行内容
            orderTitleAndCloumnMap.forEach((k,v) -> {
                HSSFCell row0Cell=row0.createCell(k);
                row0Cell.setCellValue(v.getTitle());
                row0Cell.setCellStyle(titleCellStyle);
            });

			//创建正文单元格格式
            HSSFCellStyle dataStyle = getCellStyle(resultWb,11,false, IndexedColors.BLACK.index);

			//将正文转换为excel数据
            int rowNum=1;
            for(Object data:excelDatas){

                HSSFRow row=sheet.createRow(rowNum++);
                row.setHeightInPoints(data_row_height);
				//获取对象值 key-列号 value-String值
                HashMap<Integer,String> orderValueMap=getValueMap(data);
                orderValueMap.forEach((k,v) ->{
                    HSSFCell cell=row.createCell(k);
                    cell.setCellValue(v);
                    cell.setCellStyle(dataStyle);
                        }
                );
            }

            String downFileName=fileName+".xls";
            response.setContentType("application/vnd.ms-excel; charset=UTF-8");// application/x-download
            response.setHeader("Content-Disposition", "attachment; "
                    +encodeFileName(request, downFileName));

            OutputStream outputStream = response.getOutputStream();
            resultWb.write(outputStream);
            outputStream.flush();
            outputStream.close();
            resultWb.close();

        }catch (Exception e1) {
            e1.printStackTrace();
        }


    }


    /**
     * 获取类的属性对应单元格标题和列宽
     * @param
     * @return
     */
    private static HashMap<Integer, TitleAndCloumn> getTitleAndCloumnMap(Class<?> clz) {

        HashMap<Integer, TitleAndCloumn> orderTitleAndCloumnMap=new HashMap<>();

        Field[] fs = clz.getDeclaredFields();
        for(Field f:fs) {
            f.setAccessible(true);
            if(f.isAnnotationPresent(ExcelResources.class)) {
                Integer order=f.getAnnotation(ExcelResources.class).order();
                String title=f.getAnnotation(ExcelResources.class).title();
                int cloumn=f.getAnnotation(ExcelResources.class).cloumn();

                TitleAndCloumn titleAndCloumn=new TitleAndCloumn(title,cloumn);
                orderTitleAndCloumnMap.put(order,titleAndCloumn);
            }
        }

        return orderTitleAndCloumnMap;

    }












    public HSSFCellStyle getCellStyle(HSSFWorkbook workbook,int fontSize,boolean isBoleaWeight,short color){

        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中

        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderL
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值