在工作中经常会遇到导出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。
好了,老铁,今天就到这,下期再互相学习。