@Override
public void modelexport(HttpServletResponse response) throws IOException {
//===方法一
String templatePath=this.getClass().getClassLoader().getResource("templates/model.xlsx").getPath();
InputStream is = new FileInputStream(new File(templatePath));
Workbook workbook = new XSSFWorkbook(is);
org.apache.poi.ss.usermodel.Sheet sheet =workbook.getSheetAt(0); //获取到第一个工作表
Row row1=sheet.createRow(1);
row1.createCell(1).setCellValue("asdfasdfsafd");
Row row6=sheet.createRow(6);
row6.createCell(1).setCellValue("sdafsdafsd");
Row row7=sheet.createRow(7);
row7.createCell(1).setCellValue("sadfasdfsadfd");
//清空response
response.reset();
//设置response的Header
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//重要点
// String filename = new String(fileName.getBytes(), "iso8859-1") + dateFormat.format(new Date().getTime())+".xls";
response.addHeader("Content-Disposition", "attachment;filename=example.xlsx");
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
// response.setCharacterEncoding("UTF-8");
//将excel写入到输出流中
workbook.write(os);
os.flush();
os.close();
// log.info("设置浏览器下载成功!");
//===方法二
// ClassPathResource resource = new ClassPathResource("templates/233.xlsx");
// boolean isFile = resource.isFile();
// if(!isFile){ //如果不存在返回
// return;
// }
// String path = resource.getFile().getPath();
// //获取文件路径 /* 数据写入模板文件中 */
// // 更改文件名编码
// String fileName = "ex.xlsx";
// String gFileName = URLEncoder.encode(fileName, "UTF-8");
// //如进行下载名为:文件(3).txt,下载时显示名为:文件+(3).txt --空格变为了+号
// //解决办法如下
// String dFileName = gFileName.replaceAll("\\+", "%20");
// InputStream in = null; Workbook exl = null;
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// try {
// in = new FileInputStream(path);
// exl = WorkbookFactory.create(in);
// Sheet sheet1 = exl.getSheetAt(0);
// int rowNums = sheet1.getLastRowNum();
// //模板的行数0开始,返回值比行数小1
// Row row = sheet1.createRow( 1 );
// row.createCell(2).setCellValue("sadfasdfgsfsafsdafafsa"); //序号
//
// //激活浏览器弹出窗口
// response.setContentType("application/x-msdownload");
// //浏览器弹出窗口显示的文件名
// response.addHeader("Content-Disposition", "attachment;filename=" + dFileName);
// exl.write(out);
// //in = new ByteArrayInputStream(out.toByteArray());
// response.getOutputStream().write(out.toByteArray());
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (InvalidFormatException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// try {
// if (exl != null) {
// exl.close();
// } if (out != null) {
// out.close();
// } if (in != null) {
// in.close();
// }
// } catch (IOException ex) {
// ex.printStackTrace();
// }
// }
}