博主第一次导出,踩了很多坑,最坑的是,本地能导出,但是一旦上传服务器就over了,没办法,只能换,参考了其他的博客,避免一些问题,共学习吧。话不多说,直接上代码。(博主用的是谷歌浏览器)
1.首先是controller层
@ResponseBody
@GetMapping("/Excel")
R Excel(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params) throws Exception { //按照你项目的实际需要,根据什么条件导出,就传什么参数
List<Waybill> waybills = waybillService.list(params);
Export.main(request, response, waybills);
return “成功 ”;
}
2.公用类Export
@SuppressWarnings({ "deprecation" })
public class Export {
public static void main(HttpServletRequest request, HttpServletResponse response, List<Waybill> dataList) throws Exception {
String sheetName = "运单数据";
String titleName = "运单数据";
String fileName = "运单数据";
int columnNumber = 3;
int[] columnWidth = { 10, 10, 10 };
String[] columnName = { "序号", "运单号", "运单"};
new Export().exportWithResponse(sheetName, titleName, fileName, columnNumber, columnWidth, columnName, dataList, response);
}
public void exportWithResponse(String sheetName, String titleName, String fileName, int columnNumber,
int[] columnWidth, String[] columnName, List<WaybillListDTO> dataList,HttpServletResponse response)
throws Exception {
if (columnNumber == columnWidth.length && columnWidth.length == columnName.length) {
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
//统一设置列宽