java 导出Excel文件

在工作中经常会遇到导出excel列表的文件是一件常见的事,今天呢,给大家介绍一个简单的例子,废话不多说,直接上干货,前后端都有哦!

后端代码:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
import java.io.FileOutputStream;
 
public class ExcelExportExample {
    public static void main(String[] args) throws Exception {
        Workbook workbook = new XSSFWorkbook(); // 创建工作簿
        Sheet sheet = workbook.createSheet("ExampleSheet"); // 创建工作表
 
        // 创建标题行
        Row titleRow = sheet.createRow(0);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("示例标题");
 
        // 填充数据
        for (int i = 1; i <= 10; i++) {
            Row row = sheet.createRow(i);
            Cell cell1 = row.createCell(0);
            Cell cell2 = row.createCell(1);
            cell1.setCellValue("数据" + i);
            cell2.setCellValue("数据" + (i * 2));
        }
 
        // 导出到文件
        try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {
            workbook.write(outputStream);
        }
 
        workbook.close(); // 关闭工作簿释放资源
    }
}

前端:

前端一般接收文件通常使用<a>标签,或者javaScipt的fetch Api

<!DOCTYPE html>
<html>
<head>
    <title>Excel 导出示例</title>
</head>
<body>
    <a href="/api/download/excel" download="export.xlsx">下载Excel</a>
 
    <script>
        // 或者使用JavaScript的fetch API来获取文件流并下载
        document.querySelector('a').addEventListener('click', async (event) => {
            event.preventDefault();
            const response = await fetch('/api/download/excel');
            const blob = await response.blob();
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'export.xlsx';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        });
    </script>
</body>
</html>

确保后端的接口没有问题,并且/api/download/excel接口返回Excel文件流时,响应头应当设置为Content-Disposition: attachment; filename="export.xlsx" 以及适当的Content-Type,例如application/vnd.openxmlformats-officedocument.spreadsheetml.sheet。

好了,老铁,今天就到这,下期再互相学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值