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()  
    }  
      
相关推荐
愿你天黑有灯下雨有伞18 小时前
Java使用FastExcel实现Excel文件导入
java·excel
爆爆凯18 小时前
Excel 导入导出工具类文档
java·excel
凌康ACG1 天前
springboot打包二次压缩Excel导致损坏
spring boot·后端·excel
诸葛大钢铁2 天前
Excel转PDF的三种方法
笔记·职场和发展·pdf·excel
小小薛定谔2 天前
java操作Excel两种方式EasyExcel 和POI
java·python·excel
CodeCraft Studio2 天前
DHTMLX Suite 9.2 重磅发布:支持历史记录、类Excel交互、剪贴板、拖放增强等多项升级
javascript·excel·交互·表格·dhtmlx·grid·网格
小阳睡不醒2 天前
小白成长之路-Elasticsearch 7.0 配置
大数据·elasticsearch·excel
奋进的孤狼2 天前
【Excel】使用vlookup函数快速找出两列数据的差异项
excel
不讲废话的小白2 天前
解锁高效Excel技能:摆脱鼠标,快速编辑单元格
计算机外设·excel
CodeCraft Studio2 天前
Excel处理控件Aspose.Cells教程:使用 Python 在 Excel 中创建甘特图
python·excel·项目管理·甘特图·aspose·aspose.cells