springboot实现数据库中数据导出Excel功能

1 下载jar包


            org.apache.poi
            poi
            4.0.0
        
        
            org.apache.poi
            poi-ooxml
            3.15
        

2 导出Excel

public class ExcelController {


    //创建表头
    private void createTitle(HSSFWorkbook workbook, HSSFSheet sheet){
        HSSFRow row = sheet.createRow(0);
        //设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
        sheet.setColumnWidth(0,30*256);
        sheet.setColumnWidth(1,30*256);
        sheet.setColumnWidth(3,17*256);

        //设置为居中加粗
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setBold(true);
    //    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setFont(font);

        HSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue("商品名称");
        cell.setCellStyle(style);


        cell = row.createCell(1);
        cell.setCellValue("商品分类");
        cell.setCellStyle(style);

        cell = row.createCell(2);
        cell.setCellValue("点击量");
        cell.setCellStyle(style);

        cell = row.createCell(3);
        cell.setCellValue("咨询量");
        cell.setCellStyle(style);

        cell = row.createCell(4);
        cell.setCellValue("收藏量");
        cell.setCellStyle(style);
    }

    //生成excel
    //  @GetMapping(value = "/getExcel")
    @ApiOperation(value = "导出Excel")
    @RequestMapping(value = "/getExcel",method = RequestMethod.GET)
    public String getUser(HttpServletResponse response) throws Exception{     //[ {b=b1, c=c1, a=a1}, {b=b2, c=c1, a=a1}, {b=b1, c=c1, a=a2}, {b=b2, c=c1, a=a2} ]
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("统计表");
        createTitle(workbook,sheet);
        List> rows =[ {goodsName=b1, clickCount=c1, collectionCount=a1}, {goodsName=b2, clickCount=c1, collectionCount=a1}, {goodsName=b1, clickCount=c1, collectionCount=a2}, {goodsName=b2, clickCount=c1, collectionCount=a2} ];
        //设置日期格式
        HSSFCellStyle style = workbook.createCellStyle();
        style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

        //新增数据行,并且设置单元格数据
        int rowNum=1;
        for (int i = 0; i < rows.size() ; i++) {
            HSSFRow row = sheet.createRow(rowNum);
            row.createCell(0).setCellValue((String) rows.get(i).get("goodsName"));
            row.createCell(1).setCellValue((String) rows.get(i).get("firstClass")+" - "+(String) rows.get(i).get("twoClass"));
            row.createCell(2).setCellValue(String.valueOf(rows.get(i).get("clickCount")));
            row.createCell(3).setCellValue(String.valueOf(rows.get(i).get("ConsultationCount")));
            row.createCell(4).setCellValue(String.valueOf(rows.get(i).get("collectionCount")));
            HSSFCell cell = row.createCell(3);
            cell.setCellStyle(style);
            rowNum++;
      }

        String fileName = "商品统计";

        //生成excel文件
        //buildExcelFile(fileName, workbook);
        //浏览器下载excel
        // 将文件存到浏览器设置的下载位置
        // 指定下载的文件名
        // +new String(filename.getBytes("gbk"), "iso8859-1")+
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".xls");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
      //  response.setContentType("application/vnd.ms-excel");
        OutputStream out = response.getOutputStream();
        try {
            try {
                workbook.write(out);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "1";
        } catch (Exception e) {
            e.printStackTrace();
            return "2";
        } finally {
            out.close();
        }

    }
}

3 导入Excel

@PostMapping("upload")
	public MsgResponse upload(MultipartFile file) {
		if (file==null) {
			return error("file不能为空");
		}
		List answers = new ArrayList<>();
		try {
			HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
			//有多少个sheet
			int sheets = workbook.getNumberOfSheets();
			for (int i = 0; i < sheets; i++) {
				HSSFSheet sheet = workbook.getSheetAt(i);
				//获取多少行
				int rows = sheet.getPhysicalNumberOfRows();
				Answer answer = null;
				//遍历每一行,注意:第 0 行为标题
				for (int j = 1; j < rows; j++) {
					answer = new Answer();
					 //获得第 j 行
					HSSFRow row = sheet.getRow(j);
					answer.setSelections(row.getCell(1).getStringCellValue());//单选
					answer.setCheckes(row.getCell(2).getStringCellValue());//多选
					answer.setContent(row.getCell(3).getStringCellValue());//简答
					answers.add(answer);
				}
			}
		
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
			return error(e.getMessage());
		}
		return success(answers);
	}

你可能感兴趣的:(springboot)