下载excel

1.引入依赖

XML 复制代码
 <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.5</version>
        </dependency>
        <!--&lt;!&ndash; Poi-tl Word 模板引擎&ndash;&gt;-->
        <dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.12.2</version>
        </dependency>

2.示例代码

java 复制代码
public download(String id, HttpServletResponse response){

    File file = null;
try{
 Item item = itemService.fetchById(id);
InputStream in = new ClassPathResource("/template/item.xlsx").getInputStream();
File temp = File.createTempFile("temp","xlsx");
OutputStream out = new FileOutputStream(temp);
IOUtils.copy(in,out);//apache poi
out.flush();
out.close();
in.close();

//基于临时文件通过输入流生成xlsx对象并写入数据
XSSFWorkbook workbook = new XSSFWorkbook(temp);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.createRow(2);
row.createCell(0).setCellValue(item.getStudentId());
row.createCell(1).setCellValue(item.getName());
row.createCell(2).setCellValue(item.getSex());

//输出流生成导出的文件
String fileName = String.format("学生信息下载%s.xlsx",DateUtil.format(DateUtil.date(),"yyyyMMddHHmmss"));
//DateUtil 引用的是hutool
file = new File(fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
workbook.write(fileOutputStream);
fileOutputStream.flush():
fileOutputStream.close();
//把文件写到response的输出流中 最后再删除两个中间文件
response.reset();
response.setContentType("application/vnd.ms-excel; charset=utf-8");
// 解决下载的excel报错问题
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition",String.format("attachment; filename=%s",URLEncoder.encode(fileName, StandardCharsets.UTF_8.displayName())));

exportFile(response, new FileInputStream(file));


}catch(Exception e){

    throw new RuntimeException(e.getMessage());
}finally {
    if(null != file) file.delete();


}

return "ok";


}

public static void exportFile(HttpServletResponse response, InputStream is){

    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;
try{
os = response.getOutputStream();
bis = new BufferedInputStream(is);
int i = bis.read(buff);
while(i!=-1){
    os.write(buff, 0, buff.length);
    os.flush();
    i = bis.read(buff);


}


}catch (IOException e){

    e.printStackTrace();
}finally {

    if(null != bis){
    try{
        bis.close();

}catch (IOException e){
    e.printStackTrace();
}

}

if( os != null){

    try{
        os.close();

}catch (IOException e ){
  e.printStackTrace();
}

}

}


}

前端接收时,需要用blob进行接收

即将response.type = "blob"

示例代码

javascript 复制代码
download().done(res=>{
    const url = URL.createObjcetURL(res);//创建一个指向Blob的URL
    const a = document.createElement("a");//创建一个a标签用于下载
    a.href = url;
let fileName = `学生信息${new Date().format("yyyyMMddhhmmssSSS")}.xlsx`;
a.download = fileName; // 设置下载文件名
document.body.appendChild(a);//将a标签添加到文档中以触发下载
a.click();//模拟点击下载文件
document.body.removeChild(a);//移除a标签
    



})
相关推荐
能工智人小辰5 分钟前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT5 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄8 分钟前
设计模式之外观模式
java·设计模式·外观模式
qq_3938282223 分钟前
办公文档批量打印器 Word、PPT、Excel、PDF、图片和文本,它都支持批量打印。
windows·word·powerpoint·excel·软件需求
知其然亦知其所以然1 小时前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
harmful_sheep1 小时前
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存
java·spring·缓存
星辰大海的精灵1 小时前
如何确保全球数据管道中的跨时区数据完整性和一致性
java·后端·架构
大大。1 小时前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端
nc_kai1 小时前
Flutter 之 每日翻译 PreferredSizeWidget
java·前端·flutter
Codebee1 小时前
OneCode:AI时代的先锋——注解驱动技术引领开发范式变革
java