您收到的接口返回的是一个 excel 文件流字符串,但需要将其转换成 excel 格式以便前端导出。以下是如何实现这一功能:
服务端转换
- 在服务端中接收前端请求并调用三方接口获取数据。
- 将获取到的字符串流数据转换为字节数组。
- 创建一个 bytearrayinputstream 实例,将字节数组读入。
- 使用 easyexcel 框架进行excel 写入和导出。
easyexcel 写入和导出
使用 easyexcel 框架可以方便地进行 excel 写入和导出。示例代码如下:
import com.alibaba.excel.excelwriter; import com.alibaba.excel.excelwriterbuilder; import com.alibaba.excel.write.metadata.writesheet; public class exportexcel { public static void export(bytearrayinputstream inputstream, httpservletresponse response) { try (servletoutputstream outputstream = response.getoutputstream()) { excelwriterbuilder builder = new excelwriterbuilder(); excelwriter writer = builder.file(outputstream) .exceltype(exceltypeenum.xlsx) .autoclosestream(true) .build(); writesheet sheet = easyexcel.writersheet().build(); writer.write(inputstream, sheet); response.setcontenttype("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); string filename = urlencoder.encode("导出文件", "utf-8"); response.setheader("content-disposition", "attachment;filename=" + filename); response.setheader("pragma", "public"); response.setheader("cache-control", "no-store"); response.addheader("cache-control", "max-age=0"); outputstream.flush(); } catch (exception e) { e.printstacktrace(); } } }
服务端调用示例
在服务端中,可以使用 resttemplate 调用三方接口并获取响应数据,再调用 exportexcel.export 方法将数据转换成 excel 文件。
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; @RestController @RequestMapping("/api") public class ExcelController { @Autowired private RestTemplate restTemplate; @RequestMapping(value = "/export", method = RequestMethod.POST) public void export(@RequestBody Map<String, Object> paramMap, HttpServletResponse response) { String url = "https://third-party-api.com/export"; HttpEntity<String> requestEntity = RestTemplateHttpUtils.buildHttpEntity(paramMap); byte[] bytes = restTemplate.postForObject(url, requestEntity, byte[].class); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ExportExcel.export(inputStream, response); } }
通过以上步骤,即可将三方接口返回的字符串流数据转换成 excel 文件并导出给前端。