excel模板先设置批注(就是对应一个list在excel中 循环取值)
html页面(简单块)
<div class="btn_box" id = "exporta">
<span class="export cur" onclick="excelExportAll()">
导出
</span>
</div>
<div class="change_infor left">余额汇总表</div>
js代码(涉及重点)
function excelExportAll() {
//类型选中得值
var selectVal = $('#code').val();
//关键字
var sq = $("#sqSearch").val();
var end = $("#endPicker").val();
window.location.href = BaseUtil.getCxtPath() + "/flow/export?code=" + selectVal + "&sq=" + sq + "&end=" + end;
}
ChangePage.prototype.init = function () {
$('.change_infor').click(function () {
$('#exporta').show();
$('.rjz_wrepper').show();
$('.change_infor').css({'background': '#2d7ec4'})
})
}
new ChangePage();
后台Java代码
@RequestMapping(value = "/export")
public void export(String code, String sq, String end, HttpServletRequest request, HttpServletResponse response) {
log.info("Parameter---{}---{}---Method---export", code, sq);
User currentUser = LoginUtil.getCurrentUser(request);
String currentUserName = currentUser.getUserLoginName();
CompanyVo companyVo = rpcCompanyService.get(sq);
String sign = "";
List<String> authCodeList = new ArrayList<>();
SignVo codeAuthList = this.getCodeAuthList(request);
if(!ObjectUtils.isEmpty(codeAuthList)) {
sign = codeAuthList.getSign();
authCodeList = codeAuthList.getAuthCodeList();
}
List<Map<String, Object>> excelInfoList = this.rpcFlowService.buildExcelInfo(currentUserName, end, sq, code, authCodeList, sign);
Map<String, Object> map1 = new HashMap<>();
map1.put("sq", companyVo.getPlazaShortName());
try {
String path = GetResource.class.getClassLoader().getResource("excel/uplist/bD.xls").getPath();
JxlsUtils.exportExcel(path, "余额汇总表统计.xls",excelInfoList, map1, response, request);
} catch (ExcelException e) {
e.printStackTrace();
}
}
JxlsUtils工具类中方法
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.util.JxlsHelper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
@Slf4j
public class JxlsUtils {
/**
* <p>
* 自定义excel模板导出excel-浏览器导出<br>
* </p>
* <p>
*
* @param templateExcelURL
* excel模板路径(包含至excel文件名)
* @param customeExcelName
* 自定义导出的excel文件名称(默认名称:Excel+年月日时分秒)
* @param list
* 导出数据的List<Map<String, Object>>, 不批量导出时可传入null,excel中取值遍历示例:
* jx:each(items="list" var = "temp" lastCell = "H12")->H12是指A12-H12行往下遍历
* jx:area(lastCell="H13")->H13是指表格范围A1-H13
* @param param
* 导出数据的Map<String, Object>,可传入null,
* excel中取值时示例(${param.参数名称}):${param.name}
* @param response
* HttpServletResponse
* @throws ExcelException
* 自定义异常,成功无返回,无异常 void,失败异常返回错误原因(e.getMessage())
* </p>
*/
public static void exportExcel(String templateExcelURL, String customeExcelName,List<Map<String, Object>> list, Map<String, Object> param,
HttpServletResponse response, HttpServletRequest request) throws ExcelException {
if (StringUtils.isBlank(templateExcelURL)) {
throw new ExcelException("Excel模板URL不能为空");
}
File file = new File(templateExcelURL);
if (file.isDirectory()) {
throw new ExcelException("Excel导出模板路径需包含模板文件名称");
}
if (!file.exists()) {
throw new ExcelException("Excel导出模板文件不存在,请联系管理人员添加模板");
}
if (StringUtils.isBlank(customeExcelName)) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
customeExcelName = "Excel" + simpleDateFormat.format(new Date()) + ".xls";
} catch (Exception e) {
throw new ExcelException("Excel新建默认名称日期转换异常,请重试");
}
} else {
if (!customeExcelName.contains(".xls")) {
customeExcelName += ".xls";
}
}
Context context = new Context();
context.putVar("list", list);
context.putVar("param", param);
InputStream inputStream = null;
OutputStream outputStream = null;
log.info("***************导入Excel模板开始***************");
try {
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
customeExcelName = URLEncoder.encode(customeExcelName, "utf-8");
customeExcelName = customeExcelName.replace("+", "%20"); //IE下载文件名空格变+号问题
} else {
customeExcelName = new String(customeExcelName.getBytes("utf-8"), "ISO8859-1");
}
// 设置响应
response.setHeader("Content-Disposition", "attachment;filename=\""
+ customeExcelName + "\"");
response.setContentType("application/vnd.ms-excel");
//将模板放在项目中
//InputStream in = ExportExcel.class.getResourceAsStream("/template/" + templateName);
inputStream = new BufferedInputStream(new FileInputStream(templateExcelURL));
outputStream = response.getOutputStream();
JxlsHelper jxlsHelper = JxlsHelper.getInstance();
Transformer transformer = jxlsHelper.createTransformer(inputStream, outputStream);
/*-------------------- 给模板添加自定义功能 ----------------------------*/
JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator)transformer.getTransformationConfig().getExpressionEvaluator();
Map<String, Object> funcs = new HashMap<String, Object>();
//eg:${utils:dateFmt(date,"yyyy-MM-dd")}-格式化日期
funcs.put("utils", new JxlsUtils());
evaluator.getJexlEngine().setFunctions(funcs);
jxlsHelper.processTemplate(context, transformer);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
throw new ExcelException("Excel导出异常,请重试");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
throw new ExcelException("Excel导出异常,inputStream.close异常");
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
throw new ExcelException("Excel导出异常,outputStream.close异常");
}
}
}
}
}
模板导出功能记录(zijin)