生成excel模板,并下载
@ApiOperation("下载加班记录模板或加班支付记录模板")
// @PreAuthorize("@el.check('jobPostChangeRecord:import')")
@GetMapping("template-{type}")
public void downloadTemplate(@PathVariable String type, HttpServletResponse response) {
String fileName = StringUtils.isNotBlank(type) && type.equals("1") ? "work" : "work_pay";
String sheetName = StringUtils.isNotBlank(type) && type.equals("1") ? "加班记录模板" : "加班支付记录模板";
List<String> userList = new ArrayList<>();
userList.add("员工姓名");
userList.add("员工工号");
userList.add("部门");
userList.add("当前所在项目");
if (StringUtils.isNotBlank(type) && type.equals("1")) {
userList.add("加班类型");
} else {
userList.add("支付形式");
}
userList.add("开始时间");
userList.add("结束时间");
userList.add("加班时长");
try {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(sheetName);
fileName += ".xlsx";//设置要导出的文件的名字
//新增数据行,并且设置单元格数据
int rowNum = 1;
String[] headers = userList.toArray(new String[userList.size()]);
//headers表示excel表中第一行的表头
XSSFRow row = sheet.createRow(0);
//在excel表中添加表头
for (int i = 0; i < headers.length; i++) {
XSSFCell cell = row.createCell(i);
XSSFRichTextString text = new XSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.flushBuffer();
workbook.write(response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
导出excel
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("商品信息表");
Result<List<Map<String, Object>>> resultQuery = shoppingFacade.pcExportExcel(map);
List<Map<String , Object>> list = resultQuery.getData();
String fileName = "shopping"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";//设置要导出的文件的名字
//新增数据行,并且设置单元格数据
int rowNum = 1;
String[] headers = { "商品名称", "商品id", "折扣", "原价", "现价"};
//headers表示excel表中第一行的表头
HSSFRow row = sheet.createRow(0);
//在excel表中添加表头
for(int i=0;i<headers.length;i++){
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//在表中存放查询到的数据放入对应的列
for (int i =0 ; i < list.size() && i <= 60000 ; i ++) {
HSSFRow row1 = sheet.createRow(rowNum);
Map<String, Object> map_ = list.get(i);
row1.createCell(0).setCellValue((String) map_.get("name"));
row1.createCell(1).setCellValue((Long) map_.get("id"));
row1.createCell(2).setCellValue((String) map_.get("discount"));
row1.createCell(3).setCellValue((Long) map_.get("price"));
row1.createCell(4).setCellValue((Long) map_.get("discount_price"));
rowNum++;
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.flushBuffer();
workbook.write(response.getOutputStream());
注:此文件是导出2003版本的excel文件,如果要导出2007需要有几个地方变动:
XSSFWorkbook
XSSFSheet
XSSFRow
HSSFCell
HSSFCellStyle