springboot使用jxls导出excel

1.引入依赖

        	
        
		    org.springframework.boot
		    spring-boot-starter-parent
		    2.0.6.RELEASE
		    
	    
		
        
		
			org.jxls
			jxls
			2.3.0
		

		
			org.jxls
			jxls-poi
			1.0.9
		

		
			net.sf.jxls
			jxls-core
			1.0.5
		

2.excel工具类



import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.UUID;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

public class ExcelUtil {

	/**
	 * 下载excel
	 *
	 * @author Wu JiaXin
	 * @date 2018年12月6日
	 * @param sourcePath	模板路径
	 * @param beanParams	excel内容
	 * @return
	 * @throws ParsePropertyException
	 * @throws InvalidFormatException
	 * @throws IOException
	 */
	public static ResponseEntity downLoadExcel(String sourcePath, Map beanParams)
			throws ParsePropertyException, InvalidFormatException, IOException {
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	//读取模板
	InputStream is =ExcelUtil.class.getClassLoader().getResourceAsStream(sourcePath);
	XLSTransformer transformer = new XLSTransformer();
	//向模板中写入内容
	Workbook workbook = transformer.transformXLS(is, beanParams);
	//写入成功后转化为输出流
	workbook.write(os);
	//配置Response信息
	HttpHeaders headers = new HttpHeaders();
	String downloadFileName = UUID.randomUUID().toString() + ".xlsx";
	//防止中文名乱码
	downloadFileName = new String(downloadFileName.getBytes("UTF-8"), "ISO-8859-1");
	headers.setContentDispositionFormData("attachment", downloadFileName);
	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	//返回
	return new ResponseEntity(os.toByteArray(), headers, HttpStatus.CREATED);
}

3.controller调用

	@RequestMapping("/export")
	//返回ResponseEntity使浏览器下载
	public ResponseEntity exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//查询参数
		Map params = new HashMap();
		//结果集
		List list = stdService.selectAllForExportExcel(params);
		Map beanParams = new HashMap();
		beanParams.put("list", list);
		//下载表格
		return ExcelUtil.downLoadExcel("static/excel/aaa.xlsx",beanParams);
	}

4.模板存放位置

springboot使用jxls导出excel_第1张图片

5.模板

springboot使用jxls导出excel_第2张图片

6.导出的excel

springboot使用jxls导出excel_第3张图片

 

你可能感兴趣的:(springboot使用jxls导出excel)