直接上代码
public String data(HttpServletResponse response) throws Exception {
// 创建excel
XSSFWorkbook wb = new XSSFWorkbook();
// 创建sheet
XSSFSheet sheet = wb.createSheet();
//设置宽度
sheet.setColumnWidth(0,6*1000);
sheet.setColumnWidth(1,6*1000);
//sheet.setColumnWidth(2,6*1000);
//sheet.setColumnWidth(3,6*1000);
//设置统一高度
// short s = 500;
//sheet.setDefaultRowHeight(s);
// 创建行
XSSFRow row = sheet.createRow(0);
//row.setHeight(s);
// 创建单元格
XSSFCell cell = row.createCell(0);
cell.setCellValue("序号");
//XSSFCellStyle cellStyle = wb.createCellStyle();
//cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); //设置填充方案
//cellStyle.setFillForegroundColor(new XSSFColor(new Color(92, 144,181))); //设置填充颜色
//cell.setCellStyle(cellStyle);
XSSFCell cell1 = row.createCell(1);
cell1.setCellValue("姓名");
//模拟数据
Map<String, String> map = new HashMap<>();
map.put("1", "ll");
map.put("2", "dxf");
map.put("3", "zz");
Set<String> strings = map.keySet();
int i=0;
for (String string : strings) {
++i;
XSSFRow row1 = sheet.createRow(i);
XSSFCell a0 = row1.createCell(0);
cell2.setCellValue(string);
XSSFCell a1 = row1.createCell(1);
cell3.setCellValue(map.get(string));
}
// 生成一个伪随机数
Random random = new Random();
int w = random.nextInt(999999999);
// xls本地缓存路径
// xlsFileLocalPath = req.getSession().getServletContext().getRealPath("upload") +"distribute" + w + ".xls";
String xlsFileLocalPath = "distribute" + w + "y.xls";
try(FileOutputStream files = new FileOutputStream(xlsFileLocalPath);){
wb.write(files);
wb.close();
}
/* 读取文件 */
File file = new File(xlsFileLocalPath);
/* 如果文件存在 */
if (file.exists()) {
String fileName = URLEncoder.encode("模板.xlsx", "utf-8");
response.reset();
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
int fileLength = (int) file.length();
response.setContentLength(fileLength);
/* 如果文件长度大于0 */
if (fileLength != 0) {
/* 创建输入流 */
try (InputStream inStream = new FileInputStream(file);
ServletOutputStream servletOS = response.getOutputStream()) {
byte[] buf = new byte[4096];
/* 创建输出流 */
int readLength;
while (((readLength = inStream.read(buf)) != -1)) {
servletOS.write(buf, 0, readLength);
}
servletOS.flush();
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
}else {
throw new Exception("导出失败,生成文件未找到!");
}
FileUtile.deleteFile(file);
return null;
}