elment生成excel以及下载到本地

elment-ui框架中excel导出存在封装方法,但如果要去修改excel文件样式,还需要修改框架源代码,并且也存在自定义字段需要导出时,使用框架中自带导出方法,无法满足其需求,因此针对上述两点,我在elment-ui框架基础上自己重新写了excel生成的方法,希望能帮助到有同样需求的小伙伴。

1.Vue前台代码

 <i  class="el-icon-download" @click="handleExport" title="导出"></i>

 /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      console.log(this.queryParams);
      this.$confirm("是否确认导出所有数据项?" , "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          //全局loading开启
          this.loading2 =Loading.service({ fullscreen: true ,text:"文件正在导出中,请稍后!"});
          return exportInfo(queryParams);
        }).then(response => { 
          this.download(response.msg);
          //关闭loading2
          this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
            this.loading2.close();
          });
        }).catch(()=>{});
    },

2.后台java接口代码

  /**
     * 导出资产信息列表
     */
	  @GetMapping("/exportData")
	  public AjaxResult exportData(Info info) {
    	//excel中sheet数量
//    	int sheetNumber = (fileContent.size()/65535)+1;
		// ------------------------------------追加列,获取表格每列的title
		List<String> fileTr = new ArrayList<String>();
		//列的title
		fileTr.add("ID");
		fileTr.add("编号");
		fileTr.add("名称");
		fileTr.add("类别");
		fileTr.add("部门");
		fileTr.add("时间");
		//获取到需要下载的数据信息
		List<Info> fileContent = infoService.exportInfoList(info);
            	
		// ------------------------------------excel表的生成及下载
		// 1.创建SXSSFWorkbook对象(excel的文档对象)
    	SXSSFWorkbook wb;
    	//判断有多少条数据导出
    	if(1000 < fileContent.size() && fileContent.size() < 65535) {
    		wb = new SXSSFWorkbook(65535);
    	}else {
    		wb = new SXSSFWorkbook(1000);
    	}
		OutputStream out = null;
        try
        {
    		// 2.建立新的sheet对象(excel的表单),并对sheet也设置名称
    		SXSSFSheet sheet = wb.createSheet("data");
    		// 在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
    		SXSSFRow row1 = sheet.createRow(0);
    		// 创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
    		SXSSFCell cell = row1.createCell(0);

            // 产生一行
            Row row = sheet.createRow(0);
            int column = 0;
   		
            //3.创建样式对象
            CellStyle cellStyle = wb.createCellStyle();

    		//字体设置
    		Font font = wb.createFont();
    		//font.setBold(true);
    		font.setFontName("Calibri");
    		font.setFontHeight((short) 280);
    		cellStyle.setFont(font);
    		cell.setCellStyle(cellStyle);
    		
    		// 设置单元格内容
    		String fileName = "info";
    		cell.setCellValue(fileName);
    		// 合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
    		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 28));
    		//设置单元格宽度
    		sheet.setColumnWidth(0, 5300);
    		    		
    		// 在sheet里创建第二行
    		SXSSFRow row2 = sheet.createRow(1);
    		row2.setHeightInPoints(30);
    		// 创建单元格并设置单元格内容
    		CellStyle cellHeaderStyle = wb.createCellStyle();    		
    		cellHeaderStyle.setBorderBottom(BorderStyle.THIN); //下边框
    		cellHeaderStyle.setBorderLeft(BorderStyle.THIN);//左边框
    		cellHeaderStyle.setBorderTop(BorderStyle.THIN);//上边框
    		cellHeaderStyle.setBorderRight(BorderStyle.THIN);//右边框
    		cellHeaderStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//填充单元格
    		cellHeaderStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());//填充颜色
    		cellHeaderStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直
    		cellHeaderStyle.setAlignment(HorizontalAlignment.CENTER);// 水平
    		Font fontHearder = wb.createFont();
    		fontHearder.setBold(true);
    		fontHearder.setColor(Font.COLOR_NORMAL);
    		//font.setFontName("宋体");
    		fontHearder.setFontHeight((short) 180);
    		cellHeaderStyle.setFont(fontHearder);
    		//表格每列title生成
    		for(int i=0;i<fileTr.size();i++) {						
    			row2.createCell(i).setCellStyle(cellHeaderStyle);
    			row2.getCell(i).setCellValue(fileTr.get(i));	
    		}
    		
    		CellStyle cellBodyStyle = wb.createCellStyle();
    		cellBodyStyle.setBorderBottom(BorderStyle.THIN); //下边框
    		cellBodyStyle.setBorderLeft(BorderStyle.THIN);//左边框
    		cellBodyStyle.setBorderTop(BorderStyle.THIN);//上边框
    		cellBodyStyle.setBorderRight(BorderStyle.THIN);//右边框

    		// 在sheet里创建第三行,表中填充数据
    		for(int i=0;i<fileContent.size();i++) {
    			SXSSFRow row3 = sheet.createRow(2+i);
    			
    			//固定列数据
    			//id
    			row3.createCell(0).setCellValue(fileContent.get(i).getId().toString());
    	    	row3.getCell(0).setCellStyle(cellBodyStyle);
    	    	//编号
    	    	row3.createCell(1).setCellValue((String)fileContent.get(i).getNo());
    	    	row3.getCell(1).setCellStyle(cellBodyStyle);
    	    	//名称
    	    	row3.createCell(2).setCellValue((String)fileContent.get(i).getName());
    	    	row3.getCell(2).setCellStyle(cellBodyStyle);
    			//类别
    	    	row3.createCell(3).setCellValue((String)fileContent.get(i).getType());
    	    	row3.getCell(3).setCellStyle(cellBodyStyle);
    	    	//部门
    	    	row3.createCell(4).setCellValue((String)fileContent.get(i).getDeptName());
    	    	row3.getCell(4).setCellStyle(cellBodyStyle);
				//时间
    	    	if(fileContent.get(i).getCreateTime() == null) {
    	    		row3.createCell(5).setCellValue("");       	   
    	    	}else {
    	    		row3.createCell(5).setCellValue(fileContent.get(i).getCreateTime().toString());        	    	
    	    	}
 	
    		}
			//设置文件名称,样式为"Data_"+当前日期(yyyyMMddHHmmss)
    		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    		Calendar calendar = Calendar.getInstance();
    		String dateName = df.format(calendar.getTime());
        	String filename = "Data_"+dateName+".xlsx";
        	//获取下载路径
        	String file = getAbsoluteFile(filename);
            out = new FileOutputStream(file);
            wb.write(out);
            return AjaxResult.success(filename);
        }
        catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
            throw new CustomException("导出Excel失败,请联系网站管理员!");
        }finally{
            if (wb != null) {
                try{
                    wb.close();
                }catch (IOException e1){
                    e1.printStackTrace();
                }
            }
            if (out != null){
                try  {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
	
    }
    
    /**
     * 获取下载路径
     * 
     * 
     * 
     * @param filename 文件名称
     */
    public String getAbsoluteFile(String filename)
    {
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值