Springboot项目导出excel表功能

修改list内容即可
package com.ias.teacherPC.common.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.pool.ObjectPool;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ias.admin.common.controller.BaseController;
import com.ias.admin.common.service.StudentService;
import com.ias.admin.eduAdmin.pojo.ArrCoursePO;
import com.ias.admin.eduAdmin.pojo.StuCoursePO;
import com.ias.admin.eduAdmin.pojo.TeaClaDetaPO;
import com.ias.admin.eduAdmin.service.ArrCourseService;
import com.ias.admin.eduAdmin.service.CourseService;
import com.ias.admin.eduAdmin.service.StuCourseService;
import com.ias.admin.eduAdmin.service.TeaClaDetaService;
import com.ias.admin.eduAdmin.service.TeachClassService;
import com.ias.admin.eduAdmin.service.TermService;

@Controller
@RequestMapping("/tp/Excel")
public class ExcelUtil extends BaseController {
   @Autowired
   TermService termService;
   @Autowired
   CourseService courseService;
   @Autowired
   TeachClassService teachClassService;
   @Autowired
   ArrCourseService arrCourseService;
   @Autowired
   StudentService studentService;
   @Autowired
   StuCourseService stuCourseService;
   @Autowired
   TeaClaDetaService teaClaDetaService;

   @ResponseBody
   @GetMapping("excel")
    public void excel( @RequestParam Map<String, Object> map,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        @SuppressWarnings("resource")
        HSSFWorkbook wb = new HSSFWorkbook();
        Object[]numberlist = null;
        List<Object> temp= null;
        List<List<Object>> all = null;
        HSSFSheet sheet = wb.createSheet("table");  //创建table工作薄
        HSSFRow row;
        HSSFCell cell;
      //找出所有課程id
      List<ArrCoursePO> arrCoursePOs1 =  arrCourseService.list(map);
      map.put("teacherId", this.getTeacherId());
      if( !arrCoursePOs1.isEmpty() ){
         //找出term_id course_id teach_class_id 符合條件的學生
         Map<String,Object> teaClaDetKey = new HashMap<String,Object>();
         teaClaDetKey.put("teachClassId", map.get("teachClassId"));
         List<TeaClaDetaPO> teaClaDetaPOs =  teaClaDetaService.list(teaClaDetKey);

         List<Integer> arrCourseIds = new ArrayList<>();
         for(ArrCoursePO arrCoursePO : arrCoursePOs1){
            arrCourseIds.add(arrCoursePO.getId());
         }
         System.out.println(arrCourseIds);

         //考勤情況
         List<List<StuCoursePO>> List = new ArrayList<List<StuCoursePO>>();
         List<StuCoursePO> list;
         Map<String,Object> stu_numKey = new HashMap<String,Object>();
         for (TeaClaDetaPO teaClaDetaPO : teaClaDetaPOs) {
            list = new ArrayList<StuCoursePO>();
            stu_numKey.put("studentId", teaClaDetaPO.getStudentId());
            stu_numKey.put("arrCourseIds", arrCourseIds);
            List<StuCoursePO> stCous = stuCourseService.TPAttendForm(stu_numKey);
            /*for (ArrCoursePO ArrCoursePO : arrCoursePOs1) {
               stu_numKey.put("arrCourseId", ArrCoursePO.getId());
               stCous = stuCourseService.list(stu_numKey);
               if(!stCous.isEmpty()){
                  list.add(stCous.get(0));
               }
            }*/
            List.add(stCous);
            stu_numKey.clear();
         }

         //表格數字
         List<String> number = new ArrayList<String>();
         for(int num = 1;num<=List.get(0).size();num++){
            number.add(String.valueOf(num));
         }
         number.add(0,"学生学号");
         number.add(1,"学生姓名");
         number.add(2,"学生班级");
         numberlist = number.toArray();
         all = new ArrayList<List<Object>>();
         List<Object> temp2 ;
         for (int i = 0; i < teaClaDetaPOs.size(); i++) {
            temp2 = new ArrayList<Object>();
            TeaClaDetaPO teaClaDetaPO = teaClaDetaPOs.get(i);
            temp2.add(teaClaDetaPO.getStudentNumber());
            temp2.add(teaClaDetaPO.getStudentName());
            temp2.add(teaClaDetaPO.getClassName());
            for (int j = 0; j < List.get(i).size(); j++) {
               /*<span th:case="1">√</span>
               <span th:case="0">×</span>
               <span th:case="-1">o</span>
                <span th:case="-2">△</span>
               <span th:case="-3">●</span>
                * */
               if(List.get(i).get(j).getAttend() == 1){
                  temp2.add("√");
               }else if(List.get(i).get(j).getAttend() == 0){
                  temp2.add("×");
               }else if(List.get(i).get(j).getAttend() == -1){
                  temp2.add("o");
               }else if(List.get(i).get(j).getAttend() == -2){
                  temp2.add("△");
               }else{
                  temp2.add("●");
               }
               
            }
            all.add(temp2);
         }
      }
      Object[][] datas = {{" ", " ", " ","节次(两节算一次课)√表示正常,×表示旷课,o表示迟到,△表示迟到,●表示请假"},numberlist};
      for (int i = 0; i < datas.length; i++) {
           temp = new ArrayList<Object>();
           Object [] a = datas[i];
           if(a != null){
              for (int j = 0; j < a.length; j++) {
                 temp.add(a[j]);
              }
              all.add(i,temp);
           }
        }

        for(int i = 0; i < all.size(); i++) {
            row = sheet.createRow(i);//创建表格行
            for(int j = 0; j < all.get(i).size(); j++) {
                cell = row.createCell(j);//根据表格行创建单元格
                cell.setCellValue(String.valueOf(all.get(i).get(j)));
            }
        }
           ByteArrayOutputStream os = new ByteArrayOutputStream();
           wb.write(os);
           byte[] content = os.toByteArray();
           InputStream is = new ByteArrayInputStream(content);
           response.reset();
           response.setContentType("application/vnd.ms-excel;charset=utf-8");
           response.setHeader("Content-Disposition", "attachment;filename=table.xls");
           
                 ServletOutputStream out = response.getOutputStream();
              BufferedInputStream bis = null;
              BufferedOutputStream bos = null;
         
              try {
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(out);
                byte[] buff = new byte[2048];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                  bos.write(buff, 0, bytesRead);
                }
              } catch (Exception e) {
                e.printStackTrace();
              } finally {
                if (bis != null)
                  bis.close();
                if (bos != null)
                  bos.close();
              }
//        wb.write(new FileOutputStream("D:/table22.xls"));//这行是直接写到本地的
    }

}

 

效果图:

### 实现 Vue 和 Spring Boot 项目Excel 文件导出 #### 后端实现 (Spring Boot) 为了高效处理大量数据并减少内存占用,推荐采用阿里巴巴开源的 EasyExcel 库来实现出口功能[^2]。 在 `pom.xml` 中引入所需依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.0.5</version> </dependency> <!-- 防止 slf4j 的依赖冲突 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> ``` 创建用于导出的数据模型类,并添加必要的注解以便于映射到 Excel 格列上。例如,在 `Notice.java` 类中定义字段及其对应的头名称。 编写控制器方法以响应前端请求并返回 Excel 流给客户端下载: ```java @RestController @RequestMapping("/notice") public class NoticeController { @GetMapping("/export-excel") public void export(HttpServletResponse response) throws IOException { // 设置HTTP响应头部信息 response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); String fileName = URLEncoder.encode("通知公告", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); List<Notice> notices = noticeService.findAll(); // 假设有一个服务层获取所有记录 try ( OutputStream out = response.getOutputStream(); ) { EasyExcel.write(out, Notice.class).sheet("Sheet1").doWrite(notices); } } } ``` #### 前端实现 (Vue.js) 对于前端部分,则是在页面按钮点击事件触发时向服务器发起 GET 请求,并设置合适的 HTTP 头部参数让浏览器识别这是一个文件下载操作[^3]。 修改 `Notice.vue` 组件中的模板和脚本如下所示: ```html <template> <div> <!-- ...其他HTML结构... --> <el-form-item> <button type="button" @click="handleExport">导出Excel</button> </el-form-item> </div> </template> <script> import axios from 'axios'; export default { name: 'Notice', methods: { handleExport() { const url = '/api/notice/export-excel'; axios({ method: 'GET', url, responseType: 'blob', // 关键配置项,示这是二进制流而非JSON对象 }).then((response) => { const linkElement = document.createElement('a'); let blob = new Blob([response.data], {type : 'application/octet-stream'}); let urlToDownload = window.URL.createObjectURL(blob); linkElement.setAttribute('href', urlToDownload ); linkElement.setAttribute('download', '通知公告.xlsx'); linkElement.style.display = 'none'; document.body.appendChild(linkElement); linkElement.click(); linkElement.remove(); }); }, }, }; </script> ``` 这样就完成了整个流程的设计与编码工作,当用户访问该页面并点击“导出Excel”按钮后即可获得由后台生成的通知公告列形式的 Excel 文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值