问题描述
所以我有一个Spring控制器,我想创建一个Excel文件并返回它,以便它被浏览器下载。
So I have a Spring controller, and I'd like to create an Excel file and return it so that it is downloaded by the browser.
我正在使用JEXcelApi。
I'm using JEXcelApi.
这是我的控制器代码
@RequestMapping(value="/excel/cols/{colString}/rows/{rowString}/", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> exportExcel(HttpServletResponse response,
@PathVariable List<String> colString,
@PathVariable List<String> rowString) throws JSONException, IOException, WriteException {
WritableWorkbook workbook = Workbook.createWorkbook(new File("exported.xls"));
WritableSheet sheet = workbook.createSheet("Exported",0);
String[] cols = colString.get(0).split(",");
String[] rows = rowString.get(0).split(",");
for(int i = 0; i < cols.length;i++){
Label label = new Label(i,0, cols[i]);
sheet.addCell(label);
}
int excelCol = 0;
int excelRow = 1;
for(int i = 0; i < rows.length;i++){
Label label = new Label(excelCol,excelRow, rows[i]);
sheet.addCell(label);
excelCol++;
if((i+1) % cols.length == 0){
excelCol = 0;
excelRow++;
}
}
workbook.write();
workbook.close();
return null;
}
我该怎么做?我怀疑可以设置一些内容标题。我知道一种方法是使用Spring的Abstract Excel视图类,但是有一个更简单的方法?
How do I do that? I suspect there's some content header I can set. I know one method is to use Spring's Abstract Excel view class, but is there a simpler method?
推荐答案
您需要设置 Content-Disposition
p>
You need to set the Content-Disposition
header.
response.setHeader("Content-disposition","attachment; filename=" + yourFileName);
并将字节直接写入响应 OutputStream
。
and write your bytes directly to the response OutputStream
.
File xls = new File("exported.xls"); // or whatever your file is
FileInputStream in = new FileInputStream(xls);
OutputStream out = response.getOutputStream();
byte[] buffer= new byte[8192]; // use bigger if you want
int length = 0;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
以上是比较老的。您可以使用。 将按照上面的建议复制字节。 Spring MVC使您更简单,而不是让您与Servlet规范中的接口交互。
The above is relatively old. You can construct a ResponseEntity
with FileSystemResource
now. A ResourceHttpMessageConverter
will then copy the bytes, as I have suggested above, for you. Spring MVC makes it simpler for you rather than having you interact with interfaces from the Servlet specification.
这篇关于从Spring返回Excel可下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!