poi多sheet,模板导出数据


  /**
     * 导出Excel
     * @param response 响应对象
     * @param headName 表头
     * @param  List     数据
     */
    public static void exportExcel(HttpServletResponse response, String headName, List<数据对象> list) throws IOException {

        //读取模板
        Resource resource=new ClassPathResource("file/模板.xlsx");
        Workbook workbook=new XSSFWorkbook(resource.getInputStream());

        //设置数据剧中
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        //获得 sheet
        Sheet sheet= workbook.getSheetAt(0);
		
		//获得第一行 设置表头内容
        Row headRow = sheet.getRow(0);
        Cell headRowCell = headRow.getCell(0);
        headRowCell.setCellValue(headName);

        //从第表格第三行开始写入数据,根据模板设置index开始的值
        int index=2;
        Cell cell=null;
        for (XXX xxx : list) {
			//创建行
            Row rowData = sheet.createRow(index++);
			
			/创建cell 写入值
            cell=rowData.createCell(0);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(xxx.getXXX());

            cell=rowData.createCell(1);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(xxx.getXXX());

			...
        }
		
		//如果是多数据源 导出 多个sheet  
        //获得 第二个 sheet
        Sheet sheet2= workbook.getSheetAt(1);
        
		
		//此处写法不一样

        String fileName = URLEncoder.encode("表格名称", "utf-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        workbook.write(response.getOutputStream());
		
		
		//String fileName = URLEncoder.encode("表格名称.xlsx", "utf-8");
        //response.setHeader("content-type", "application/octet-stream;charset=utf-8");
        //response.setHeader("content-disposition", "attachment; ");
        //response.setHeader("filename",fileName);
        //workbook.write(response.getOutputStream());

    }

你可能感兴趣的:(servlet,java)