poi导出值班excel

java 复制代码
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();  
}
java 复制代码
@GetMapping("/exportDutyInfo")  
public void exportDutyInfo(HttpServletResponse response) {  
    
    List<DutyInfo> dutyInfos = // 获取你的值班信息列表  
    try {  
        exportDutyInfoToExcel(dutyInfos, response);  
    } catch (IOException e) {  
        e.printStackTrace();  
        // 处理异常  
    }  
}
javascript 复制代码
<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的名称。

    java 复制代码
    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()  
    }  
      
相关推荐
不坑老师5 小时前
利用不坑盒子的Copilot,快速排值班表
microsoft·word·powerpoint·excel·copilot·wps
开开心心就好9 小时前
批量PDF转换工具,一键转换Word Excel
开发语言·前端·学习·pdf·电脑·word·excel
Fireworkitte16 小时前
Apache POI 详解 - Java 操作 Excel/Word/PPT
java·apache·excel
Prodigy_kyw20 小时前
VBA初学3----实战(VBA实现Excel转csv)
excel·vba·csv
红衣女妖仙1 天前
JXLS 库导出复杂 Excel
java·excel·jxls·java 导出 excel
吃我两拳1 天前
EasyExcel停止当前Sheet的读取,且不影响主线程及其他Sheet读取的方法
excel
qq_393828221 天前
办公文档批量打印器 Word、PPT、Excel、PDF、图片和文本,它都支持批量打印。
windows·word·powerpoint·excel·软件需求
过期的秋刀鱼!1 天前
用“做饭”理解数据分析流程(Excel三件套实战)
数据挖掘·数据分析·excel·powerbi·数据分析入门
挑战者6668881 天前
如何将Excel表的内容转化为json格式呢?
excel
干净的坏蛋1 天前
EasyExcel实现Excel复杂格式导出:合并单元格与样式设置实战
excel