springboot+vue使用poi,生成excel并且使用输出流发送到前端浏览器

发布于:2024-03-28 ⋅ 阅读:(22) ⋅ 点赞:(0)

导入的包

       <dependency>
	   	<groupId>org.apache.poi</groupId>
	   	<artifactId>poi</artifactId>
	   	<version>4.1.1</version>
	   </dependency>
	   <dependency>
	   	<groupId>org.apache.poi</groupId>
	   	<artifactId>poi-scratchpad</artifactId>
	   	<version>4.1.1</version>
	   </dependency>
	   <dependency>
	   	<groupId>org.apache.poi</groupId>
	   	<artifactId>poi-ooxml</artifactId>
	   	<version>4.1.1</version>
	   </dependency>
	   <dependency>
	   	<groupId>org.apache.poi</groupId>
	   	<artifactId>poi-ooxml-schemas</artifactId>
	   	<version>4.1.1</version>
	   </dependency>
	   <dependency>
	   	<groupId>org.apache.poi</groupId>
	   	<artifactId>ooxml-schemas</artifactId>
	   	<version>1.4</version>
	   </dependency>
	   <dependency>
	   	<groupId>org.apache.poi</groupId>
	   	<artifactId>ooxml-security</artifactId>
	   	<version>1.1</version>
	   </dependency>

前端代码

axios({
        method: 'post',
        url: '/CheckStore/DOWNLOADA',
        data: param,
        responseType: 'blob' // 告诉 axios 期望一个 blob 响应
      })
        .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]))
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', 'example.xlsx')
          document.body.appendChild(link)
          link.click()
          // 释放 URL 对象
          window.URL.revokeObjectURL(url)
        })

其中     responseType: 'blob' 是核心告诉后端返回的数据类型

	@PostMapping(value = "/DOWNLOADA")  
//	public Object exportExcel( @RequestParam("SYS") String SYS) { 
public void exportExcel( @RequestParam("SYS") String SYS,HttpServletResponse response) throws IOException { 
		System.out.println(SYS);
		RespondResultPojo respondResultPojo=new RespondResultPojo();
//	     创建Excel工作簿和工作表  
//	    Workbook workbook = new XSSFWorkbook();  
//	    Sheet sheet = workbook.createSheet("Sheet1");  
//		System.out.println("ZEB0G0PpojojsonArray.toString()");
//	    // 填充数据(这里只是示例)  
//	    Row row = sheet.createRow(0);  
//	    Cell cell = row.createCell(0);  
//	    cell.setCellValue("Hello, Excel!");  
	     设置响应头  
//	    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");  
//	    response.setHeader("Content-Disposition", "attachment; filename=example.xlsx");  
//	    // 写入输出流  
//	    ServletOutputStream outputStream = response.getOutputStream();  
//	    workbook.write(outputStream);  
//     
//	    
//	    // 刷新并关闭流  
//	    outputStream.flush();  
//	    outputStream.close();  
//	      
//	    // 关闭工作簿  
//	    workbook.close();  
    	JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < 4; i++) {
            JSONObject jsonObject = new JSONObject();  
            jsonObject.put("BGPLAC", "C1");  
            jsonObject.put("BGDIVI", "9A");
            jsonObject.put("BGOPEC", "68");
            jsonObject.put("BGITNO", "P3110KL04W30L12");
            jsonObject.put("BGCQTY", "100");
            jsonArray.add(jsonObject);
		}
        if(jsonArray == null || jsonArray.size() == 0){
            System.out.println("数据对象为空或无可操作数据.");
            return; // 跳出方法
        }
		// 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建表
        Sheet sheet = workbook.createSheet("sheet 1");
        List<String> list = new ArrayList<>();  
        
        // 向列表中添加元素  
        list.add("部门1");  
        list.add("部门2");  
        list.add("部门2");  
        list.add("型号");
        list.add("数量"); 
        // 创建行
//        for(int i=0; i<=object.size(); i++){
        for (int i = 0; i < jsonArray.size()+1; i++) {  

            Row row = sheet.createRow(i); // 创建行
            
            // 设置标题列
            if(i==0){

                Font font = workbook.createFont(); // 创建字体样式
                font.setBold(true);
                font.setFontHeightInPoints((short) 12);
                CellStyle cellStyle = workbook.createCellStyle(); // 创建表格样式
                cellStyle.setFont(font);
                cellStyle.setAlignment(HorizontalAlignment.CENTER);
//                tempMap = mapList.get(0);
//                Iterator<String> keyIterator = tempMap.keySet().iterator();
                for(int j=0;j<5;j++) {
                	Cell cell = row.createCell(j); // 创建列
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(list.get(j));
                }
            }else{// 设置值列
            Object jsonObject=jsonArray.getJSONObject(i-1);
//				  for (int i = 0; i < JSONArrayList.size(); i++) {  
//				        Object obj2 = JSONArrayList.get(i);
            JSONObject jsonObject2 = JSON.parseObject(jsonObject.toString());  
			 String bgitno = jsonObject2.getString("BGITNO");//型号  
			 String bgplac = jsonObject2.getString("BGPLAC");
			 String bgdivi = jsonObject2.getString("BGDIVI");//型号
			 String bgopec = jsonObject2.getString("BGOPEC");//型号 
			 String bgcqty = jsonObject2.getString("BGCQTY");//型号 
			 Cell cell = row.createCell(0);  
			 cell.setCellValue( bgplac);
			 Cell cell1 = row.createCell(1);  
			 cell1.setCellValue( bgdivi);
			 Cell cell2 = row.createCell(2);  
			 cell2.setCellValue( bgopec);
			 Cell cell3 = row.createCell(3);  
			 cell3.setCellValue( bgitno);
			 Cell cell4 = row.createCell(4);  
			 cell4.setCellValue( bgcqty);	      
            }
         }
       ServletOutputStream outputStream = response.getOutputStream();  
	   workbook.write(outputStream);     
	    
	    // 刷新并关闭流  
	    outputStream.flush();  
	    outputStream.close();  
//		return respondResultPojo.success("查询成功");
	}

这是没有加数据库查询的相应类型

本文含有隐藏内容,请 开通VIP 后查看