@ResponseBody
@RequestMapping(value = "excelOut")
public String excelOut(HttpServletRequest request, HttpServletResponse response) {
//建立一個模板所在文件夾及名稱template/test.xlsx
TemplateExportParams params = new TemplateExportParams("template/test.xlsx", 0, 1);
Map<String, Object> map = new HashMap<>();
List<Map<String, String>> headList = new ArrayList<>();
//這是活動表頭,如果用戶要設置的列數是不固定的,則在這里設定,如取一個list中對象作為多個列
for (int i = 0; i < 3; i++) {
Map<String, String> m = new HashMap<>();
m.put("name", "自定義表頭" + i);
m.put("code", "t.code" + i);
headList.add(m);
}
map.put("head", headList);
//組裝數據
List<Map<String, Object>> list = new ArrayList<>();
for (int i = 0; i < 8; i++) {
int s = new Random().nextInt(5) + 2;
for (int k = 0; k < s; k++) {
Map<String, Object> m = new HashMap<>();
m.put("g1", "id" + i);
m.put("g2", "2固定值" + i+(i % 2 == 0 ? "" : "\t"));
m.put("g3", "3固定值" + i);
for (int j = 0; j < 3; j++) {
m.put("code" + j, i + "code" + j);
}
m.put("list_sex", i + "sex" + k);
list.add(m);
}
}
map.put("rows", list);
params.setColForEach(true);
Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//需要合並的列,相當的數據就會合並,不合並則加(i % 2 == 0 ? "" : "\t")
PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 1, 2, 3, 4, 5, 6, 7, 8);
// FileOutputStream fos = new FileOutputStream("D:/test"+System.currentTimeMillis()+".xlsx");//存在本地磁盤
// workbook.write(fos);
// fos.close();
//設置保存的文件名
String fileName = DateUtils.getYear() + "年" + DateUtils.getMonth() + "月" + DateUtils.getDay() + "日數據表_" + System.currentTimeMillis() + ".xlsx";
//在瀏覽器中保存導出
response.reset();
response.setContentType("application/octet-stream");
try {
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
//模板圖片,可根據自己需要更改
//建立一個模板所在文件夾及名稱template/test.xlsx
