POI 導出文件以文件流形式返回

POI工具類?


import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;public class PoiUtils {/*** 導出Excel* @param sheetName sheet名稱* @param title 標題* @param values 內容* @param wb HSSFWorkbook對象* @return*/public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][]values, HSSFWorkbook wb){// 第一步,創建一個HSSFWorkbook,對應一個Excel文件if(wb == null){wb = new HSSFWorkbook();}// 第二步,在workbook中添加一個sheet,對應Excel文件中的sheetHSSFSheet sheet = wb.createSheet(sheetName);// 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制HSSFRow row = sheet.createRow(0);// 第四步,創建單元格,并設置值表頭 設置表頭居中HSSFCellStyle style = wb.createCellStyle();
//        style.setAlignment(HorizontalAlignment.CENTER); // 創建一個居中格式//聲明列對象HSSFCell cell = null;//創建標題for(int i=0;i<title.length;i++){cell = row.createCell(i);cell.setCellValue(title[i]);cell.setCellStyle(style);}//創建內容for(int i=0;i<values.length;i++){row = sheet.createRow(i + 1);for(int j=0;j<values[i].length;j++){//將內容按順序賦給對應的列對象row.createCell(j).setCellValue(values[i][j]);}}return wb;}//發送響應流方法public static void setResponseHeader(HttpServletResponse response, String fileName) {try {try {fileName = new String(fileName.getBytes(),"ISO8859-1");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}response.setContentType("application/octet-stream;charset=ISO8859-1");response.setHeader("Content-Disposition", "attachment;filename="+ fileName);response.addHeader("Pargam", "no-cache");response.addHeader("Cache-Control", "no-cache");} catch (Exception ex) {ex.printStackTrace();}}
}

導出接口
?

    @GetMapping("/exportParkOrderByPage")@ApiOperation(value = "導出訂單明細信息(默認查詢全部)", notes = "導出訂單明細信息(默認查詢全部)", response = ParkOrder.class)public void exportParkOrderByPage(@RequestParam(value = "page", required = false, defaultValue = "0") @ApiParam(required = false, defaultValue = "0", value = "當前頁數,默認從0開始") Integer page,@RequestParam(value = "limit", required = false, defaultValue = "10") @ApiParam(required = false, defaultValue = "10", value = "每一頁條數,默認10條") Integer limit,@RequestParam(value = "pkid", required = false) @ApiParam(required = false, value = "車場名稱") String pkid,@RequestParam(value = "payWay", required = false) @ApiParam(required = false, value = "線上線下(0.線上 1.線下)") String payWay,@RequestParam(value = "orderSource", required = false) @ApiParam(required = false, value = "訂單來源") String orderSource,@RequestParam(value = "userId", required = false) @ApiParam(required = false, value = "操作人") String userId,@RequestParam(value = "plateNo", required = false) @ApiParam(required = false, value = "車牌號碼") String plateNo,@RequestParam(value = "orderTimeStart", required = false) @ApiParam(required = false, value = "開始訂單時間") String orderTimeStart,@RequestParam(value = "orderTimeEnd", required = false) @ApiParam(required = false, value = "結束訂單時間") String orderTimeEnd,HttpServletResponse response) {try {log.info("++++++++++訪問/count/exportParkOrderByPage接口入參:>>>>>>pkid:" + pkid+ " payWay:" + payWay+ " orderSource:" + orderSource+ " userId:" + userId+ " plateNo:" + plateNo+ " orderTimeStart:" + orderTimeStart+ " orderTimeEnd:" + orderTimeEnd);limit = Integer.MAX_VALUE;Page<ParkOrder> requestPage = new Page<>(page, limit);Map<String, Object> requestParam = new HashMap<String, Object>();requestParam.put("pkid", pkid);requestParam.put("payWay", payWay);requestParam.put("orderSource", orderSource);requestParam.put("userId", userId);requestParam.put("plateNo", plateNo);requestParam.put("orderTimeStart", orderTimeStart);requestParam.put("orderTimeEnd", orderTimeEnd);Page<ParkOrder> parkOrderByPage = parkOrderService.getParkOrderByPage(requestPage, requestParam);List<ParkOrder> records = parkOrderByPage.getRecords();//excel標題String[] title = {"車場名稱", "車牌號碼", "訂單編號", "金額", "已付金額", "未付金額", "折扣金額", "訂單類型", "支付方式", "訂單時間", "訂單來源", "操作人", "備注"};//excel文件名String fileName = "訂單明細信息" + System.currentTimeMillis() + ".xls";//sheet名String sheetName = "訂單明細信息表";SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String[][] content = new String[records.size()][title.length];for (int i = 0; i < records.size(); i++) {//車場名稱content[i][0] = records.get(i).getPkName() == null ? "" : records.get(i).getPkName().toString();//車牌號碼content[i][1] = records.get(i).getPlateNo() == null ? "" : records.get(i).getPlateNo().toString();//訂單編號content[i][2] = records.get(i).getOrderNo() == null ? "" : records.get(i).getOrderNo().toString();//金額content[i][3] = records.get(i).getAmount() == null ? "" : records.get(i).getAmount().toString();//已付金額content[i][4] = records.get(i).getPayAmount() == null ? "" : records.get(i).getPayAmount().toString();//未付金額content[i][5] = records.get(i).getUnPayAmount() == null ? "" : records.get(i).getUnPayAmount().toString();//折扣金額content[i][6] = records.get(i).getDiscountAmount() == null ? "" : records.get(i).getDiscountAmount().toString();//訂單類型content[i][7] = "";if (records.get(i).getOrderType() != null && StrUtil.isNotBlank(records.get(i).getOrderType().toString())) {Integer orderType = Integer.valueOf(records.get(i).getOrderType().toString());switch (orderType) {case 1:content[i][7] = "臨時卡繳費";break;case 2:content[i][7] = "月卡繳費";break;case 3:content[i][7] = "VIP卡繳費";break;case 4:content[i][7] = "儲值卡充值";break;case 5:content[i][7] = "臨時卡續期";break;case 6:content[i][7] = "儲值卡繳費";break;case 12:content[i][7] = "車位預定";break;}}//支付方式content[i][8] = "";if (records.get(i).getPayWay() != null && StrUtil.isNotBlank(records.get(i).getPayWay().toString())) {Integer payType = Integer.valueOf(records.get(i).getPayWay().toString());switch (payType) {case 1:content[i][8] = "現金";break;case 2:content[i][8] = "微信";break;case 3:content[i][8] = "支付寶";break;case 4:content[i][8] = "網銀";break;case 5:content[i][8] = "電子錢包";break;case 6:content[i][8] = "優免券";break;case 7:content[i][8] = "余額";break;}}//訂單時間content[i][9] = records.get(i).getOrderTime() == null ? "" : dateFormat.format(records.get(i).getOrderTime());//訂單來源content[i][10] = "";if (records.get(i).getOrderSource() != null && StrUtil.isNotBlank(records.get(i).getOrderSource().toString())) {Integer source = Integer.valueOf(records.get(i).getOrderSource().toString());switch (source) {case 1:content[i][10] = "微信";break;case 2:content[i][10] = "APP";break;case 3:content[i][10] = "中心繳費";break;case 4:content[i][10] = "崗亭繳費";break;case 5:content[i][10] = "管理處";break;case 6:content[i][10] = "第三方平臺";break;}}//操作人content[i][11] = records.get(i).getUserId() == null ? "" : records.get(i).getUserId().toString();//備注content[i][12] = records.get(i).getRemark() == null ? "" : records.get(i).getRemark().toString();}//創建HSSFWorkbookHSSFWorkbook wb = PoiUtils.getHSSFWorkbook(sheetName, title, content, null);//響應到客戶端PoiUtils.setResponseHeader(response, fileName);OutputStream os = response.getOutputStream();wb.write(os);os.flush();os.close();log.info("++++++++++訪問/count/exportParkOrderByPage接口調用成功>>>>>>");} catch (Exception e) {e.printStackTrace();log.error("++++++++++訪問/count/exportParkOrderByPage接口系統異常原因 : +++++++++" + e.getMessage());} catch (Throwable throwable) {throwable.printStackTrace();log.error("++++++++++訪問/count/exportParkOrderByPage接口系統異常原因 : +++++++++" + throwable.getMessage());}}

前端操作
?

    handleDownload() {this.downloadLoading = trueexportParkOrderByPage(this.listQuery).then(res=>{console.log(res)var blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet這里表示xlsx類型var downloadElement = document.createElement('a');var href = window.URL.createObjectURL(blob); //創建下載的鏈接downloadElement.href = href;downloadElement.download = '訂單明細.xls'; //下載后文件名document.body.appendChild(downloadElement);downloadElement.click(); //點擊下載document.body.removeChild(downloadElement); //下載完成移除元素window.URL.revokeObjectURL(href); //釋放掉blob對象 this.downloadLoading = false;})},

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273670.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273670.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273670.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Json串和java對象進行轉時

json-lib-xxx.jarezmorph-xxx.jar //>依賴包 JsonConfig config new JsonConfig();//有選擇性的過濾掉一些屬性值 JSONUtils.getMorpherRegistry().registerMorpher( new DateMorpher(new String[] { "yyyy-MM-dd" }));//注冊一個json轉為java.util.date的日期格…

Mybatis Integer類型參數值為0時判斷為空、空字符串不通過

根據狀態查詢是&#xff0c;由于status是Integer類型&#xff0c;所以當前狀態為0時&#xff0c;變成了查詢了所有的狀態信息。 <if test"requestParam.status ! null and requestParam.status ! ">and s.status #{requestParam.status} </if> 原因&a…

BZOJ 3391: [Usaco2004 Dec]Tree Cutting網絡破壞(搜索)

這道直接遍歷一遍求出每個點的子節點數目就行了 CODE&#xff1a;#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>using namespace std;#define maxn 50010int b[maxn],q[maxn],id[maxn],ans[maxn];bool cmp(int x,int y){re…

Fast Matrix Operations

uva11992:http://uva.onlinejudge.org/index.php?optioncom_onlinejudge&Itemid8&pageshow_problem&problem3143 題意&#xff1a;給你n*m的矩陣初始化的時候矩陣里面的元素全部是0&#xff0c;對于這個矩陣有3中操作。 1 x1 y1 x2 y2 v 把&#xff08;x1 y1 x2…

linux ll命令無效

1.編輯~/.bashc vim ~/.bashc 若vi/vim命令無效&#xff0c;參考 bash: vi: command not found/bash: vim: command not found 2.重新執行剛修改的初始化文件 source ~/.bashc

jquery不同版本沖突導致低版本功能不能用

oConflict() 方法讓渡變量 $ 的 jQuery 控制權。 該方法釋放 jQuery 對 $ 變量的控制。 使用方法&#xff1a; var jq $.noConflict();//轉換控制權 jq(document).ready(function () { jq("#outside").click(function () {你的操作...... }); }); });轉載于:https:/…

struts2+jquery 實現ajax登陸

一、新建一個web項目&#xff1a;test,配置好struts2的環境(詳細配置見&#xff1a;http://www.cnblogs.com/wuweidu/p/3841297.html) 導入Jquery的js文件到項目 二、在com.action包下&#xff0c;新建一個loginAction.java loginAction.java的代碼如下 package com.action;imp…

hdu 2026 首字母變大寫

題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid2026 題目大意&#xff1a;將一個英文句子&#xff0c;每個單詞第一個首字母變大寫。 1 #include <stdio.h>2 int main (void)3 {4 int i;5 char ch[100];6 while(gets(ch))7 {8 for (i0; c…

Docker Kafka 單機版安裝

一、安裝 下載library/zookeeper并運行 docker run --name zookeeper -d -p 2181:2181 -v /etc/localtime:/etc/localtime library/zookeeper 測試zookeeper端口是否通wget IP:2181 下載wurstmeister/kafka并運行 docker run -d --name kafka -p 9092:9092 --link zookeeper…

HDU1429勝利大逃亡(續)HDU 1885 Key Task BFS+狀態壓縮+水

HDU1429 只有10把鑰匙 1<<10足夠了 標記用三維數組 用Linux好不習慣 繼續克服&#xff5e; #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <malloc.h> #include <ctype.h> #include &l…

Docker 安裝nginx,并掛載文件

創建掛載所需目錄&#xff1a; mkdir /test/server/nginx/{conf,logs,html,conf.d} /test/server/nginx/conf創建nginx.conf文件&#xff0c;并編輯: user nginx; worker_processes 1;error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid;events {wor…

http解碼-5

http://www.freebuf.com/articles/web/18084.html (1) 在 前端安全技術中常見的編碼繞過技術利用的就是不同系統間的編碼位寬(addslashes()樓哦的那個)&#xff0c;不同編碼的解碼順序(htmlParserjavascriptParser的解碼順序)&#xff0c;不同的解碼規則(unicode->ascii轉換…

IllegalArgumentException:argument type mismatch

Exception nested exception is org.apache.ibatis.reflection.ReflectionException: Could not set property id of class com.wzq.test.demo.entity.Fee with value 1211518556674199553Cause:java.lang.IllegalArgumentException: argument type mismatch 場景: 添加不傳ID使…

hadoop家族的各個成員

這篇文章不提原理&#xff0c;講講hadoop及其周邊項目的作用。 hadoop這個詞已經流行好多年了&#xff0c;一提到大數據就會想到hadoop&#xff0c;那么hadoop的作用是什么呢&#xff1f; 官方定義&#xff1a;hadoop是一個開發和執行處理大規模數據的軟件平臺。核心詞語是平臺…

ArrayList 源碼分析

介紹 ArrayList 是一個數組隊列&#xff0c;相當于 動態數組。與Java中的數組相比&#xff0c;它的容量能動態增長。 結構 ArrayList繼承于AbstractList&#xff0c;實現了List, RandomAccess, Cloneable, java.io.Serializable這些接口。如下圖&#xff1a; public class Arra…

Poj 1556 The Doors 計算幾何+最短路

其實本題非常的無腦&#xff0c;無腦拍完1A&#xff0c;寫到blog里只因為TM無腦拍也拍了很久啊 #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <climits> #include <string> #include <iostr…

String equals()方法 源碼分析

public boolean equals(Object anObject) {// :比較的引用類型&#xff0c;比較的是地址值是否相同if (this anObject) { //地址值相等&#xff0c;返回truereturn true;}// instanceOf判斷一個對象是不是某個類型的實例if (anObject instanceof String) {String anotherStrin…

Google,真的要離我們而去嗎?

Google,真的要離我們而去嗎&#xff1f; 好懷念&#xff0c;真正要解決問題&#xff0c;還得搜google!轉載于:https://www.cnblogs.com/fuyujian/p/3852444.html

Oracle 位圖索引

內容簡介: 1.位圖索引 1.1位圖索引使用注意事項; 1.2 使用位圖索引; 1.3 位圖索引對DML操作的影響; 2.位圖連接索引 2.1 明確需求后使用位圖索引; 2.1創建位圖連接索引的注意事項: 1.位圖索引: 1.1位圖索引使用注意事項: ? 一般適用于低基數列; ? 適合數據倉庫; ? 對于啟用位…

oracle服務器和客戶端字符集的查看和修改

一、什么是oracle字符集 Oracle字符集是一個字節數據的解釋的符號集合,有大小之分,有相互的包容關系。ORACLE 支持國家語言的體系結構允許你使用本地化語言來存儲&#xff0c;處理&#xff0c;檢索數據。它使數據庫工具&#xff0c;錯誤消息&#xff0c;排序次序&#xff0c;日…