Spring boot集成jxls实现导出excel功能

添加的maven依赖:

		<!-- jxsl dependency for poi -->
		<dependency>
			<groupId>org.jxls</groupId>
			<artifactId>jxls-poi</artifactId>
			<version>${jxsl.poi.version}</version>
		</dependency>
		<dependency>
			<groupId>org.jxls</groupId>
			<artifactId>jxls</artifactId>
			<version>${jxls.version}</version>
		</dependency>
		<dependency>
			<groupId>org.jxls</groupId>
			<artifactId>jxls-reader</artifactId>
			<version>2.0.3</version>
		</dependency>

导出模板类:

package com.ismartgo.uqcode.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;

/**
 * JXSL excel模板工具方法
 * <br/>
 * JXSL detail please see http://jxls.sourceforge.net/<br/>
 * User: Foy Lian
 * Date: 2017-07-04
 * Time: 17:44
 */
public class JxlsTemplate {
    /**
     * 模板路径
     */
    private static final String TEMPLATE_DIR = "/excel";

    protected static Log logger = LogFactory.getLog(JxlsTemplate.class);
    /**
     * 使用JxlsTemplate.class.getResourceAsStream load 模板
     *
     * @param template 模板名称,相当于TEMPLATE_DIR设置的路径
     * @param out      生成excel写入的输出流
     * @param params   交给jxls处理模板需要的参数
     * @throws IOException
     */
    public static void processTemplate(String template, OutputStream out, Map<String, ?> params) throws IOException {
        processTemplate(JxlsTemplate.class, template, out, params);
    }

    /**
     * 使用resourceBaseClassgetResourceAsStream load 模板
     *
     * @param resourceBaseClass class load的类
     * @param template          模板名称
     * @param out               生成excel写入的输出流
     * @param params            交给jxls处理模板需要的参数
     * @throws IOException
     */
    public static void processTemplate(Class resourceBaseClass, String template, OutputStream out, Map<String, ?> params) throws IOException {
        InputStream in = resourceBaseClass.getResourceAsStream(TEMPLATE_DIR + template);
        if (null == in) {
            logger.error("can't find excel template by path:" + TEMPLATE_DIR + template);
            throw new TemplateNotFoundException("找不到excel模板!,位置:" + TEMPLATE_DIR + template);
        }
        processTemplate(in, out, params);
    }
    /**
     * @param templateStream excel模板流
     * @param out            生成excel写入的输出流
     * @param context        jxsl上下文
     * @throws IOException
     */
    private static void processTemplate(InputStream templateStream, OutputStream out, Context context) throws IOException {
        JxlsHelper.getInstance().processTemplate(templateStream, out, context);
    }

    /**
     * @param templateStream excel模板流
     * @param out            生成excel写入的输出流
     * @param params         交给jxls处理模板需要的参数
     * @throws IOException
     */
    public static void processTemplate(InputStream templateStream, OutputStream out, Map<String, ?> params) throws IOException {
        Context context = new Context();
        if (params != null) {
            for (String key : params.keySet()) {
                context.putVar(key, params.get(key));
            }
        }
        processTemplate(templateStream, out, context);
    }


}

Controller类导出接口方法:

	@RequestMapping(value="/export", method = RequestMethod.GET)
	public void export(HttpServletResponse response,HttpServletRequest req) {
		AuthUser user = (AuthUser) req.getSession().getAttribute("loginUser");
		UqcProduct product = new UqcProduct();
		//product.setSysTenantCode(user.getSysTenantCode());
		product.setSysTenantCode("1");
		ServletOutputStream out = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		List<UqcProduct> list = productService.queryList(product);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("items", list);
		try {
			response.setHeader("Expires", "0");
			response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
			response.setHeader("Content-Disposition", "attachment; filename=\"product.xls\"");
			response.setHeader("Pragma", "public");
			response.setContentType("application/x-excel;charset=UTF-8");
			out = response.getOutputStream();
			JxlsTemplate.processTemplate("/productList_export.xls", out, params);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Excel模板:

Excel模板添加的批注:上图ID批注:zsy:jx:area(lastCell="N2")

${item.id}的批注:zsy:jx:each(items="items" var="item" lastCell="N2")

模板识别到Controller传入的items值进行for循环进行值得填充

猜你喜欢

转载自blog.csdn.net/syilt/article/details/91473055