poi导出值班excel

import org.apache.poi.ss.usermodel.*;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  
import javax.servlet.http.HttpServletResponse;  
import java.io.IOException;  
import java.util.List;  
  
public void exportDutyInfoToExcel(List<DutyInfo> dutyInfos, HttpServletResponse response) throws IOException {  
    // 创建Workbook  
    Workbook workbook = new XSSFWorkbook();  
    // 创建Sheet  
    Sheet sheet = workbook.createSheet("Duty Info");  
  
    // 创建表头  
    Row headerRow = sheet.createRow(0);  
    String[] headers = {"时间", "日志类型", "厂站", "内容"};  
    for (int i = 0; i < headers.length; i++) {  
        Cell cell = headerRow.createCell(i);  
        cell.setCellValue(headers[i]);  
    }  
  
    // 填充数据  
    for (int i = 0; i < dutyInfos.size(); i++) {  
        DutyInfo dutyInfo = dutyInfos.get(i);  
        Row row = sheet.createRow(i + 1);  
          
        Cell timeCell = row.createCell(0);  
        timeCell.setCellValue(dutyInfo.getTime().toString()); // 根据实际情况可能需要格式化  
  
        Cell logTypeCell = row.createCell(1);  
        logTypeCell.setCellValue(dutyInfo.getLogType());  
  
        Cell stationCell = row.createCell(2);  
        stationCell.setCellValue(dutyInfo.getStation());  
  
        Cell contentCell = row.createCell(3);  
        contentCell.setCellValue(dutyInfo.getContent());  
    }  
  

    // 获取当前日期并格式化为字符串  
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");  
    String currentDate = LocalDate.now().format(formatter);  
  
    // 设置响应头,包括带有当前日期的文件名  
    String fileName = "duty_info_" + currentDate + ".xlsx";  
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");  
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
  
      
  
    // 写入到输出流  
    workbook.write(response.getOutputStream());  
  
    // 关闭Workbook  
    workbook.close();  
}
@GetMapping("/exportDutyInfo")  
public void exportDutyInfo(HttpServletResponse response) {  
    
    List<DutyInfo> dutyInfos = // 获取你的值班信息列表  
    try {  
        exportDutyInfoToExcel(dutyInfos, response);  
    } catch (IOException e) {  
        e.printStackTrace();  
        // 处理异常  
    }  
}
<template>  
  <div>  
    <!-- 按钮触发下载 -->  
    <button @click="downloadDutyInfo">下载值班信息</button>  
  </div>  
</template>  
  
<script>  
export default {  
  methods: {  
    async downloadDutyInfo() {  
      try {  
        // 发送GET请求到后端API  
        const response = await fetch('/exportDutyInfo', {  
          method: 'GET',  
          // 如果需要,可以添加headers,比如认证信息  
          // headers: {  
          //   'Authorization': 'Bearer your_token_here'  
          // }  
        });  
  
        // 检查响应状态  
        if (!response.ok) {  
          throw new Error('网络响应错误');  
        }  
  
        // 创建一个blob对象用于处理二进制数据  
        const blob = await response.blob();  
  
        // 创建一个指向该对象的URL  
        const url = window.URL.createObjectURL(blob);  
  
        // 创建一个a标签用于下载  
        const a = document.createElement('a');  
        a.href = url;  
        a.download = 'duty_info.xlsx'; // 设置下载的文件名  
  
        // 触发下载  
        document.body.appendChild(a);  
        a.click();  
  
        // 清理  
        window.URL.revokeObjectURL(url);  
        document.body.removeChild(a);  
      } catch (error) {  
        console.error('下载失败:', error);  
        // 可以在这里添加错误处理逻辑,比如显示错误消息给用户  
      }  
    }  
  }  
}  
</script>
  1. EasyExcel.write()方法接受一个OutputStream作为输出目标,这里是HttpServletResponsegetOutputStream()返回的流。然后,你可以指定要写入的POJO类(这里是DutyInfo.class)和Sheet的名称。

    import com.alibaba.excel.EasyExcel;  
    import com.alibaba.excel.write.metadata.WriteSheet;  
    import javax.servlet.http.HttpServletResponse;  
    import java.io.IOException;  
    import java.net.URLEncoder;  
    import java.nio.charset.StandardCharsets;  
    import java.time.LocalDate;  
    import java.time.format.DateTimeFormatter;  
    import java.util.List;  
      
    public void exportDutyInfoToExcel(List<DutyInfo> dutyInfos, HttpServletResponse response) throws IOException {  
        // 获取当前日期并格式化为字符串  
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");  
        String currentDate = LocalDate.now().format(formatter);  
        // URL编码文件名以防止特殊字符导致的问题  
        String fileName = URLEncoder.encode("duty_info_" + currentDate + ".xlsx", StandardCharsets.UTF_8.toString());  
      
        // 设置响应头  
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");  
    
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);  
      
        // 使用EasyExcel导出数据  
        try (OutputStream outputStream = response.getOutputStream()) {  
    
            // 这里不需要显式创建Workbook或Sheet,EasyExcel会帮你处理  
    
            EasyExcel.write(outputStream, DutyInfo.class)  
                    .sheet("Duty Info")  
                    .doWrite(dutyInfos);  
        }  
      
        // 注意:由于我们使用了try-with-resources语句,outputStream会在写入完成后自动关闭  
        // 因此,我们不需要在这里显式调用outputStream.close()  
    }  
      
    

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值