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()  
    }  
      
相关推荐
IT小哥哥呀2 小时前
《纯前端实现 Excel 导入导出:基于 SheetJS 的完整实战》
前端·excel
长河2 小时前
Excel中三种数据匹配方法
excel
开开心心就好4 小时前
图片批量压缩工具:支持有损无损两种模式
java·游戏·pdf·excel·散列表·启发式算法·1024程序员节
aloha_7894 小时前
Linux常用增删改查命令
linux·运维·excel
wtsolutions5 小时前
JSON转Excel工具新增WPS插件功能,将JSON转换成WPS表格工作表数据
json·excel·wps·插件·转换·加载项·wtsolutions
heartbeat..5 小时前
介绍java中常用于处理 Excel 文件的Apache POI
java·apache·excel·poi
八饱粥5 小时前
excel数据导入mysql数据库
数据库·mysql·excel
꧁坚持很酷꧂5 小时前
Ubuntu系统下通过第三方库QtXlsx输出Excel(图文详解)
ubuntu·excel
祝威廉5 小时前
InfiniSynapse: 把PDF里的表格和Excel/业务数据联合分析
pdf·excel
承缘丶5 小时前
Excel字段清单转各类数据库建表语句的工具(开箱即用)
数据库·excel·excel转数据库建表语句