**
Excel导出空模板
**
没写前端和上一篇一样,在上一篇的基础上优化了
1.ExcelUtil工具
package com.xsl.middle_school_oa.utils;
import org.apache.poi.hssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class ExcelUtil {
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param wb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(HttpServletResponse response,
HSSFWorkbook hsswb) throws UnsupportedEncodingException {
// 第一步,创建一个HSSFWorkbook,Excel文件
if(hsswb == null){
hsswb= new HSSFWorkbook();
}
//excel标题 如果不需要字段可以不加title
String[] title = {"字段1","字段2","字段3","字段4"};
//excel文件名
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码
//excel文件名
String fileName = URLEncoder.encode("excel导入模板", "UTF-8");
//我运行时 xlsx和xls都支持,如果不支持查看依赖
//response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
//sheet名
String sheetName = "sheet1";
HSSFSheet sheet = hsswb.createSheet(sheetName);
HSSFRow row = sheet.createRow(0);
//声明列
HSSFCell cell = null;
//将标题输出
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
}
return hsswb;
}
}
2.controller
package com.xsl.middle_school_oa.controller;
import com.xsl.middle_school_oa.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
@Controller
@RequestMapping(value = "/report")
public class DownExcelController {
/**
* 导出excel表
* @return
*/
@RequestMapping(value = "/export")
@ResponseBody
public void export( HttpServletResponse response) throws Exception {
//创建HSSFWorkbook 调用Excel工具包
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(response,null);
//响应到前端
try {
OutputStream os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}