标签:变量 pre 导出 hide http header 固定 padding one
public void exportExcel(){
try {
/** 1.从数据库查出数据 */
List<User> uList = userService.findAll();
/** 2.封装数据 */
Map<String, Object> dataMap = new HashMap<String, Object>();
List<Map<String, String>> userList = new ArrayList<>(uList.size());
for (User u : uList) {
Map<String, String> rowData = new HashMap<>();
rowData.put("name", u.getName());
rowData.put("account", u.getAccount());
rowData.put("dept", u.getDept());
rowData.put("gender", u.isGender() ? "男" : "女");
rowData.put("email", u.getEmail());
userList.add(rowData);
}
dataMap.put("userList", userList);
/** 3.调用FreeMarker的Api生成Excel */
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
// 设置加载模板文件的位置
cfg.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/ftl");
// 获取模板
Template template = cfg.getTemplate("exportExcel.ftl");
// 设置response的header
HttpServletResponse response = ServletActionContext.getResponse();
// 防止乱码,设置下编码
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; filename=testExcel.xls");
// 生成Excel
template.process(dataMap, response.getWriter());
} catch (Exception e) {
e.printStackTrace();
}
}
public void exportExcel(){
try {
/** 1.从数据库查出数据 */
List<User> uList = userService.findAll();
/** 2.封装数据 */
Map<String, Object> dataMap = new HashMap<String, Object>();
List<Map<String, String>> userList = new ArrayList<>(uList.size());
for (User u : uList) {
Map<String, String> rowData = new HashMap<>();
rowData.put("name", u.getName());
rowData.put("account", u.getAccount());
rowData.put("dept", u.getDept());
rowData.put("gender", u.isGender() ? "男" : "女");
rowData.put("email", u.getEmail());
userList.add(rowData);
}
dataMap.put("userList", userList);
/** 3.调用FreeMarker的Api生成Excel */
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
// 设置加载模板文件的位置
cfg.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/ftl");
// 获取模板
Template template = cfg.getTemplate("exportExcel.ftl");
// 设置response的header
HttpServletResponse response = ServletActionContext.getResponse();
// 防止乱码,设置下编码
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; filename=testExcel.xls");
// 生成Excel
template.process(dataMap, response.getWriter());
} catch (Exception e) {
e.printStackTrace();
}
}
JavaWeb开发中采用FreeMarker生成Excel表格
标签:变量 pre 导出 hide http header 固定 padding one
原文地址:https://www.cnblogs.com/zeng1994/p/9295284.html