eg:
@Override标签:Java,excel,header,createCell,POI,setCellValue,response,manufacturer,row From: https://www.cnblogs.com/sensenh/p/18345202
public void exportExcel(HttpServletResponse response) throws Exception{
// 创建Excel文档
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("设备厂商");
// 创建表头
XSSFRow header = sheet.createRow(0);
header.createCell(0).setCellValue("ID");
header.createCell(1).setCellValue("厂商名称");
header.createCell(2).setCellValue("信用编码");
header.createCell(3).setCellValue("厂商简称");
header.createCell(4).setCellValue("地址");
header.createCell(5).setCellValue("联系人");
header.createCell(6).setCellValue("所在城市");
header.createCell(7).setCellValue("联系人手机号");
header.createCell(8).setCellValue("设备类型名称");
// 填充数据
List<ManufacturerVo> list = recManufacturerDao.findAll();
int rowIndex = 1;
for (ManufacturerVo manufacturer : list) {
XSSFRow row = sheet.createRow(rowIndex++);
row.createCell(0).setCellValue(manufacturer.getId());
row.createCell(1).setCellValue(manufacturer.getName());
row.createCell(2).setCellValue(manufacturer.getCredit());
row.createCell(3).setCellValue(manufacturer.getAbbreviation());
row.createCell(4).setCellValue(manufacturer.getAddress());
row.createCell(5).setCellValue(manufacturer.getContactPerson());
row.createCell(6).setCellValue(manufacturer.getDescription());
row.createCell(7).setCellValue(manufacturer.getContactPhone());
row.createCell(8).setCellValue(manufacturer.getDeviceCategoryName());
}
String percentEncodedFileName = percentEncode("设备厂商");
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(percentEncodedFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(percentEncodedFileName);
// 设置响应头信息
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", contentDispositionValue.toString());
response.setHeader("download-filename", percentEncodedFileName);
// response.setContentType("application/vnd.ms-excel");
// response.setHeader("Content-Disposition", "attachment; filename=users.xlsx");
// 将Excel文档写入响应流中
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
/**
* 百分号编码工具方法
*
* @param s 需要百分号编码的字符串
* @return 百分号编码后的字符串
*/
public static String percentEncode(String s) throws UnsupportedEncodingException {
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\\+", "%20");
}