package com.lalala.ami.common; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.doreen.core.annotation.Api; import com.doreen.core.annotation.Item; import com.doreen.core.annotation.JSON; import com.doreen.core.aop.bean.Result; import com.doreen.core.exception.ErrorEnum; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Map; /** * @author * @version 1.0 * @date 2020/6/19 0019 17:09 * @description */ @RestController public class ExportExcelController { @Value("${server.port}") private String port; private Log log = LogFactory.getLog(ExportExcelController.class); @Api("导出Excel") @RequestMapping("/excel") @JSON({@Item(name = "url", desc = "请求路径", must = true), @Item(name = "param", desc = "请求参数", must = true), @Item(name = "head", desc = "要生成的表头", must = true)}) public void excel(@RequestHeader Map<String, String> header, @RequestBody JSONObject jsonObject, HttpServletResponse httpResponse) throws URISyntaxException, IOException { String url = "http://127.0.0.1:" + port + "/" + jsonObject.getString("url"); HttpClient httpClient = HttpClients.createDefault(); URIBuilder uriBuilder = new URIBuilder(url); HttpPost postParam = new HttpPost(uriBuilder.build()); header.keySet().forEach(key -> { //首字母和横杠后面的字母转换成大写 key = this.convertToUpcase(key); if (!("Content-Length".equals(key) || "content-length".equals(key))) { postParam.setHeader(key, header.get(key)); } }); JSONObject param = jsonObject.getJSONObject("param"); StringEntity entity = new StringEntity(param.toString(), Charset.defaultCharset()); entity.setContentType("application/json"); postParam.setEntity(entity); HttpResponse response = httpClient.execute(postParam); int code = response.getStatusLine().getStatusCode(); if (code != 200){ return; } exportExcel(response, jsonObject, httpResponse); } //不知为何后端接受到的请求头是小写的,为了模拟真实请求只能再转换为大写 private String convertToUpcase(String key) { char[] chars = key.toCharArray(); StringBuilder res = new StringBuilder(); for (int i = 0; i <chars.length ; i++) { if(i==0){ res.append(Character.toUpperCase(chars[i])); continue; } if('-'==chars[i]){ i++; res.append("-").append(Character.toUpperCase(chars[i])); continue; } res.append(chars[i]); } return res.toString(); } private void exportExcel(HttpResponse response, JSONObject jsonObject, HttpServletResponse httpResponse) throws IOException { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(); sheet.setDefaultColumnWidth((short) 18); //获取表头 JSONObject head = jsonObject.getJSONObject("head"); String[] heads = head.keySet().toArray(new String[]{}); //获取数据 HttpEntity entity = response.getEntity(); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader( new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8), 8 * 1024); StringBuilder entityStringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { entityStringBuilder.append(line); } //生成JsonObject JSONObject resJsonObj = JSONObject.parseObject(entityStringBuilder.toString()); JSONObject data = resJsonObj.getJSONObject("data"); if(data == null){ return; } JSONArray list = data.getJSONArray("list"); //创建标题行 Row row = sheet.createRow(0); for (int i = 0; i < heads.length; i++) { Cell cell = row.createCell(i); cell.setCellType(CellType.STRING); cell.setCellValue(head.getString(heads[i])); } //创建数据行 for (int i = 0; i < list.size(); i++) { Row dataRow = sheet.createRow(i + 1); JSONObject vals = (JSONObject) list.get(i); for (int j = 0; j < heads.length; j++) { Cell cell = dataRow.createCell(j); cell.setCellType(CellType.STRING); cell.setCellValue(vals.getString(heads[j])); } } httpResponse.setContentType("application/octet-stream"); httpResponse.setHeader("Content-Disposition", "attachment;fileName=" + "export.xls"); ServletOutputStream outputStream = httpResponse.getOutputStream(); workbook.write(outputStream); } catch (Exception e) { e.printStackTrace(); } finally { if(bufferedReader!=null){ bufferedReader.close(); } } } } 贴一下前端代码: $(document).ready(function(){ $("button").click(function(){ request(); }); function request () { const req = new XMLHttpRequest(); req.open('POST', 'http://127.0.0.1:8080/excel', true); req.responseType = 'blob'; req.setRequestHeader('Content-Type', 'application/json'); req.onload = function() { const data = req.response; const a = document.createElement('a'); const blob = new Blob([data]); const blobUrl = window.URL.createObjectURL(blob); download(blobUrl) ; }; req.send(JSON.stringify({ "url": "lvdn/query/freezeData/getGridMeterFreezeData", "param": { "Id": "4fbs3a547092", "mepe":"sub", "dataType":"day", "startTime":"2020-05-01 00:00:00", "endTime":"2020-07-01 00:00:00" }, "head":{ "meterName":"电表名称", "meterNo":"电表序号", "kat":"电能示值" } })); }; function download(blobUrl) { const a = document.createElement('a'); a.style.display = 'none'; a.download = '11111.xls'; a.href = blobUrl; a.click(); document.body.removeChild(a); } }); 说几个坑:1.这种方式前端需要特殊处理,XMLHttpRequest用这个东西,具体怎么样我不会,百度就好。
2.后端接收到requestHeader之后无怨无gu的转换成了小写,为了模拟真实请求我们要再改回大写。
3. httpResponse.setContentType("application/octet-stream"); httpResponse.setHeader("Content-Disposition", "attachment;fileName=" + "export.xls");这个响应头不加的话据说下载的文件打不开。
4.适用场景:为统一的返回接口做xls包装,相当于我们后端去调用原来接口,把数据拿到再包装。