当前位置:主页 > java教程 > Springboot数据导出

Springboot与vue实现数据导出方法具体介绍

发布:2023-04-09 09:30:02 59


给网友朋友们带来一篇相关的编程文章,网友通谷丝根据主题投稿了本篇教程内容,涉及到Springboot数据导出、Vue数据导出、Springboot数据导出相关内容,已被939网友关注,下面的电子资料对本篇知识点有更加详尽的解释。

Springboot数据导出

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

前言

这两天在项目中使用到Java的导入导出功能,以前对这块有一定了解,但是没有系统学习过,今天在这里进行记录,方便以后查阅。

一、需求

项目的需求是将项目中的JSON实体数据导出为.json文件,导出的文件,可以作为元数据导入进行实体初始化。项目不是使用普通的springboot框架(普通的springboot框架很容易完成),因此走了一些弯路,在这篇文章中,将先讲解使用springboot框架进行导出,然后再讲解非springboot框架的导出。

二、Springboot进行数据导出

1.Java后端代码

@RequestMapping("/download")
public void download(String path, HttpServletResponse response) {
	// 固定写法
	response.setContentType("application/OCTET-STREAM;charset=UTF-8");
	response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
	File file = new File(path);
	try {
	    InputStream fis = new FileInputStream(file);
	    OutputStream out = new BufferedOutputStream(response.getOutputStream());
	    byte[] buffer = new byte[1024];
	    int len;
	    while ((len = fis.read(buffer)) != -1) {
	        out.write(buffer, 0, len);
	        out.flush();
	    }
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}

导出操作时,返回值类型必须为void,由于项目有指定的返回格式(返回值类型不能为void),导致类型不匹配报错,在新写了处理方法之后,解决了这个问题。 这里使用了BufferedOutputStream,能加快导出速度。不用BufferedOutputStream,只使用response.getOutputStream()也是可以的。此外,这里使用了循环写入输出流中,而不是一次写入。

2.Vue前端代码

    handleExport(row) {
      const id = row.id || this.ids
      const name = row.name || this.names[0]
      const code = row.code || this.codes
      const params = {
        exportCodes: JSON.stringify(code)
      }
      this.download('/Thingmax/Things/Export',  params,  name + '.json')
    },

download方法第一个参数是导出方法的响应路由,第二个参数为导出时携带的参数,第三个参数为导出的文件名称。

3.其他几种Java后端导出方法

1、使用BufferedOutputStream,一次性写入

exportEntities.put("Entities", entities);
String content = exportEntities.toJSONString();
try {
	BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
	out.write(content.getBytes(StandardCharsets.UTF_8));
	out.flush();
	out.close();
} catch (Exception e) {
     throw new RuntimeException(e);
 }

一次性将数据读取到内存,通过响应输出流输出到前端

2、不使用BufferedOutputStream,循环写入

InputStream inputStream = new FileInputStream(path);
ServletOutputStream outputStream = response.getOutputStream();
   byte[] b = new byte[1024];
   int len;
   //从输入流中读取一定数量的字节,并将其存储在缓冲区字节数组中,读到末尾返回-1
   while ((len = inputStream.read(b)) > 0) {
       outputStream.write(b, 0, len);
   }

到此这篇关于Springboot与vue实现数据导出方法具体介绍的文章就介绍到这了,更多相关Springboot数据导出内容请搜索码农之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持码农之家!


参考资料

相关文章

网友讨论