自己总结的excel空模板导出
1.ExcelUtil
这里没有设置任何的样式
public class ExcelUtil {
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param hsswb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, HSSFWorkbook hsswb){
//创建一个HSSFWorkbook,对应一个Excel文件
if(hsswb== null){
hsswb = new HSSFWorkbook();
}
//在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = hsswb.createSheet(sheetName);
//声明行 设置行的起始位置
HSSFRow row = sheet.createRow(0);
//声明列
HSSFCell cell = null;
/**
* 创建标题
* 1.cell是根据title的长度来决定的,输出自己需要展示的表头
*/
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
}
return hsswb;
}
}
2.在controller层
@Controller
@RequestMapping(value = "/excel")
public class DownExcelController {
/**
* 导出excel空的模板(只有要展示的表头)
* @return
*/
@RequestMapping(value = "/downexcel")
@ResponseBody
public void export( HttpServletResponse response) throws Exception {
//excel这里title根据自己的需求设置
String[] title = {"字段1","字段2","字段3","字段4"};
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码
//excel文件名
String fileName = URLEncoder.encode("excel模板", "UTF-8");
//这里的xls和xlsx都支持
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
//sheet名
String sheetName = "sheet1";
//创建HSSFWorkbook 调用excel工具将 sheet名和表头传过去
HSSFWorkbook hsswb= ExcelUtil.getHSSFWorkbook(sheetName, title, null);
//前端响应
try {
OutputStream os = response.getOutputStream();
//将处理好的数据写到hsswb中
hsswb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.前端
<button type="button" class="layui-btn layui-btn-sm" id="excelDown">导出Excel</button>
//触发跳转
$('#excelDown').click(function(){
window.location.href="/excel/downexcel";
});
|