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()  
    }  
      
相关推荐
LAM LAB6 天前
【VBA】Excel指定单元格范围内字体设置样式,处理导出课表单元格
excel·vba
在这habit之下7 天前
Keepalived学习总结
excel
Youngchatgpt7 天前
如何在 Excel 中使用 ChatGPT:自动化任务和编写公式
人工智能·chatgpt·自动化·excel
开开心心就好7 天前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划
D_C_tyu7 天前
Vue3 + Element Plus | el-table 多级表头表格导出 Excel(含合并单元格、单元格居中)第二版
vue.js·elementui·excel
骆驼爱记录7 天前
WPS页码设置:第X页共Y-1页
自动化·word·excel·wps·新人首发
Cxiaomu8 天前
Python 文件解析: Excel / Word / PDF 的解析、处理、预览与下载
python·word·excel
2501_930707788 天前
如何使用C#代码从 PDF 中提取表格并另存为Excel文件
pdf·excel
pacong8 天前
B生所学EXCEL
人工智能·excel