今天在公司开发时,遇到这样一个需求:可以让客户下载excel文件。我写了代码之后,忽然意识到我这样的生成文件是本地的,也就是说是保存在服务器的。
有这样一个解决方案:先看Service层:
@Override
public String downloadPieceCost(PieceCostParam pieceCostParam) {
XMLExcel e = new XMLExcel();
e.setSheetName("线索收费明细表");
String[] title = {"序号","机构名称","购买时间","数据包名称","购买线索条数","线索单价","线索收费"};
try {
List<PieceCostVO> pieceCostVOList = costRelatedService.getAllPieceCost(pieceCostParam);
List<List<Object>> data = new ArrayList<>();
for (PieceCostVO vo:pieceCostVOList){
List<Object> row = new ArrayList<>();
row.add(1+"");
row.add(vo.getCompanyName());
row.add(vo.getPurchaseTime());
row.add(vo.getDataPackName());
row.add(vo.getDataSum());
row.add(vo.getDataCost());
row.add(vo.getCostSum());
data.add(row);
}
String excel = e.buildExcel(title, data);
return excel;
} catch (Exception ex) {
ex.printStackTrace();
logger.error("导出报表失败" + ex.getMessage());
return e.buildExcel(title, null);
}
}
其次是Controller层:
@RequestMapping("pieceCost")
public void callReport(
@RequestBody PieceCostParam pieceCostParam, HttpServletResponse response) throws UnsupportedEncodingException {
String excel=excelExportService.downloadPieceCost(pieceCostParam);
response.setContentType("application/vnd.ms-excel");
String fileName = "线索收费明细-" + TimeHepler.dateToString(new Date(), "ddHHmm") + ".xls";
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
OutputStream os;
try {
os = response.getOutputStream();
os.write(excel.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
返回结果:
<?xml version="1.0" encoding="UTF-8" ?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"> <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Created>Fri Aug 11 11:36:48 CST 2017</Created></DocumentProperties>
<Worksheet ss:Name="线索收费明细表">
<Table ss:ExpandedRowCount="2">
<Row>
<Cell><Data ss:Type="String">序号</Data></Cell>
<Cell><Data ss:Type="String">机构名称</Data></Cell>
<Cell><Data ss:Type="String">购买时间</Data></Cell>
<Cell><Data ss:Type="String">数据包名称</Data></Cell>
<Cell><Data ss:Type="String">购买线索条数</Data></Cell>
<Cell><Data ss:Type="String">线索单价</Data></Cell>
<Cell><Data ss:Type="String">线索收费</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="String">1</Data></Cell>
<Cell><Data ss:Type="String">杭州电子放假大学</Data></Cell>
<Cell><Data ss:Type="String">2017/08/10 16:10:26</Data></Cell>
<Cell><Data ss:Type="String">杭州电子放假大学的数据包</Data></Cell>
<Cell><Data ss:Type="Number">0</Data></Cell>
<Cell><Data ss:Type="String">0.00</Data></Cell>
<Cell><Data ss:Type="String">0.00</Data></Cell>
</Row>
</Table>
</Worksheet>
</Workbook>
具体前端怎么生成excel文件,就不管啦!!!!!!!!!!
开玩笑开玩笑 ,工资重要工资重要!等有空看看怎么直接导出文件。
一百年后。。。。我终于知道怎么直接导出文件啦。集体看我的这篇文章─=≡Σ(((つ•̀ω•́)つ-------》Springmvc 生成并且下载文件--直接在浏览器下载。