excel模板下载(模板导出)
一、将excel模板放在java服务的,然后前端点击按钮来下载
1.前端代码:
/**下载模板 */ handleDownload(){ let url = process.env.VUE_APP_BASE_API; // window.location.href=`${url}/kylinApi/downloadTemplate1` window.location.href=`${url}/kylinApi/downloadTemplate` }
2.后台代码:
@GetMapping(value = "/downloadTemplate") public void downFrozenTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = "专家信息.xlsx"; ServletOutputStream out; response.setCharacterEncoding("UTF-8"); response.setContentType("content-type:octet-stream"); //文件在项目中的存放路径 String filePath = getClass().getResource("/template/specialistTemplate.xlsx").getPath(); String userAgent = request.getHeader("User-Agent"); if (userAgent.contains("MSIE") || userAgent.contains("Trident")) { fileName = java.net.URLEncoder.encode(fileName, "UTF-8"); } else { // 非IE浏览器的处理: fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1"); } filePath = URLDecoder.decode(filePath, "UTF-8"); response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); FileInputStream inputStream = new FileInputStream(filePath); out = response.getOutputStream(); int b = 0; byte[] buffer = new byte[65536]; while ((b = inputStream.read(buffer)) != -1) { //写到输出流(out)中 out.write(buffer, 0, b); } inputStream.close(); if (out != null) { out.flush(); out.close(); } }
二、直接通过apach poi在java端生成excel表格,然后以文件流的形式输出到前端。
1.前端代码:
/**下载模板 */ handleDownload(){ let url = process.env.VUE_APP_BASE_API; window.location.href=`${url}/kylinApi/downloadTemplate1` //window.location.href=`${url}/kylinApi/downloadTemplate` }
2.后台代码:
controller层代码:
@GetMapping(value = "/downloadTemplate1") public void downloadTemplate1(HttpServletResponse response) throws Exception { String excelName = "专家信息"; //获取需要转出的excel表头的map字段 LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>(); fieldMap.put("specialistName","姓名"); fieldMap.put("specialistOfCom","所属单位"); fieldMap.put("specialistOfDept","所属部门"); fieldMap.put("specialistOfPost","职位"); fieldMap.put("specialistType","类型"); fieldMap.put("specialistMobile","联系电话"); fieldMap.put("specialistEmail","工作邮箱"); fieldMap.put("specialistMajor","专业领域"); //导出用户相关信息 new ExportExcelUtils().export(excelName,new ArrayList<>(),fieldMap,response); }
工具类:
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class ExportExcelUtils {
/**
* 导出Excel
*
* @param excelName 要导出的excel名称
* @param list 要导出的数据集合
* @param fieldMap 中英文字段对应Map,即要导出的excel表头
* @param response 使用response可以导出到浏览器
* @param <T>
*/
public static <T> void export(String excelName, List<T> list, LinkedHashMap<String, String> fieldMap, HttpServletResponse response) {
// 设置默认文件名为当前时间:年月日时分秒
if (excelName == null || excelName == "") {
excelName = new SimpleDateFormat("yyyyMMddhhmmss").format(
new Date()).toString();
}
// 设置response头信息
response.reset();
response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
try {
response.setHeader("Content-disposition", "attachment; filename="
+ new String(excelName.getBytes("gb2312"), "ISO-8859-1") + ".xlsx");
} catch (UnsupportedEncodingException e1) {
log.info(e1.getMessage());
}
try {
//创建一个WorkBook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//在Workbook中,创建一个sheet,对应Excel中的工作薄(sheet)
HSSFSheet sheet = wb.createSheet(excelName);
//创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
//创建一个居中格式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 填充工作表
fillSheet(sheet, list, fieldMap, style);
//将文件输出
OutputStream ouputStream = response.getOutputStream();
wb.write(ouputStream);
ouputStream.flush();
ouputStream.close();
} catch (Exception e) {
log.info("导出Excel失败!");
log.error(e.getMessage());
}
}
/**
* 向工作表中填充数据
*
* @param sheet excel的工作表名称
* @param list 数据源
* @param fieldMap 中英文字段对应关系的Map
* @param style 表格中的格式
* @throws Exception 异常
*/
public static <T> void fillSheet(HSSFSheet sheet, List<T> list,
LinkedHashMap<String, String> fieldMap, HSSFCellStyle style) throws Exception {
log.info("向工作表中填充数据:fillSheet()");
// 定义存放英文字段名和中文字段名的数组
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];
// 填充数组
int count = 0;
for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}
//在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int) 0);
// 填充表头
for (int i = 0; i < cnFields.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(cnFields[i]);
cell.setCellStyle(style);
// sheet.autoSizeColumn(i);
sheet.setColumnWidth(i, 256*15+184);
}
}
}