springboot+poi开发 加载使用Excel模板导出

基于springBoot开发Excel复杂模板导出功能(所谓复杂模板指在模板里的特定表头里有不同的单元格合并以及背景色,字体颜色的填充,文本内容的对齐方式等),废话不多说,直接怼代码:
1.增加maven仓库依赖

<!-- 导出表格模板的jar支持 -->
		<dependency>
			<groupId>net.sf.jxls</groupId>
			<artifactId>jxls-core</artifactId>
			<version>1.0.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.9</version>
		</dependency>

2.定义一个用于接收导出数据的实体类

@Data
public class DemoExcelVo {
    /**
     * 序号
     */
    private String id;
    /**
     * 名称
     */
    private String name;
    /**
     * 别名
     */
    private String alias;
    /**
     * 年龄
     */
    private String age;
}

3.定义一个表格生成的实体类

/**
 * ExcelVO  表格生成
 * @author xyp
 */
@Data
public class ExcelVO {
    /**
     * Excel名称
     */
    private String fileName;
    /**
     * 模板路径
     */
    private String templateUrl;
    /**
     * 生成的Excel路径
     */
    private String templateNewUrl;
    /**
     * 表格的具体数据
     */
    private Map<String, Object> map;

    private String path;
}

3.表格导出的工具类

import java.net.URL;
import java.net.URLEncoder;
import java.io.InputStream;
import com.demo.common.StringUtils;
import com.demo.common.dto.ExcelVO;
import net.sf.jxls.transformer.XLSTransformer;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

/**
 * 导出模板工具
 *
 * @author chensq
 */
public class ExportTemplateUtil {
    /**
     * 导出不规则公共方法 .xlsx .xls两种格式
     *
     * @param excelVO  入参
     * @param response 响应结果
     */
    public void exportTemplate(ExcelVO excelVO, HttpServletResponse response) {
        URL url = this.getClass().getClassLoader().getResource("");
        assert url != null;
        String path = url.getPath();
        if (StringUtils.isNotEmpty(excelVO.getPath())){
            path = excelVO.getPath();
        }
        //获得模版路径
        String templateUrl = path + excelVO.getTemplateUrl();
        //生成的导出文件路径
        String templateNewUrl = path + excelVO.getTemplateNewUrl();

        System.out.println("+++++生成的导出文件路径:"+templateNewUrl);
        //transformer转到Excel
        XLSTransformer transformer = new XLSTransformer();
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        // 循环取出流中的数据
        byte[] b = new byte[1024];
        int len;
        try {
            // 下载本地文件 文件的默认保存名
            String fileName = URLEncoder.encode(excelVO.getFileName(), "UTF-8");
            System.out.println("----------------------下载的本地文件名称:"+fileName);
            //更新模板信息
            transformer.transformXLS(templateUrl, excelVO.getMap(), templateNewUrl);

            // 读到流中 文件的存放路径
            InputStream inStream = new FileInputStream(templateNewUrl);
            response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
        	e.printStackTrace();
        } catch (InvalidFormatException e) {
        	e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

4.创建表格模板excel文件
在这里插入图片描述
表格里的写法:
在这里插入图片描述
表格里最常用的for循环标签写法:
开头:<jx:forEach items=“${userList}” var=“user”>
结尾:</jx:forEach>

5.创建请求接口方法:

	/**
	 * 导出信息
	 * @param session
	 * @return Excel流
	 */
	@RequestMapping("/exportExcel")
	@ResponseBody
	@Log(function = "数据导出", operationType = OperationType.EXPORT)
	public void exportExcel(@RequestBody Map<String, String> param, HttpServletResponse response) {
		try{
			System.out.println(",,,,,,,,,,导出请求");
			String fileName = "导出信息维护.xlsx";
			//查询获取导出的数据
			List<DemoExcelVo> demoList = demoService.exportData(param);
			Map<String, Object> map = new HashMap<>(16);
			map.put("userList", demoList);
			ExcelVO excelVO = new ExcelVO();
			excelVO.setFileName(fileName);
			excelVO.setMap(map);
			excelVO.setTemplateUrl("static/excle/defectImageTemplate.xlsx");
			excelVO.setTemplateNewUrl("static/excle/defectImage.xlsx");
			System.out.println("+++++++++++++++++导出:"+demoList.size()+"条");
			new ExportTemplateUtil().exportTemplate(excelVO, response);
		}catch (Exception e){
			e.printStackTrace();
		}
	}

这里值得注意的是:map里的对象属性,就是表格里标签:${userList}里的属性

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值