java接⼝返回⽂件_根据接⼝⽂档书写接⼝,并在前端调⽤接⼝返回显⽰出数据(加下载)...
1 packagecom.eptok.util;2
3 importjava.io.ByteArrayOutputStream;
4 importjava.io.FileOutputStream;
5 importjava.io.IOException;6
importjava.io.OutputStream;7 importjava.io.UnsupportedEncodingException;8 importjava.math.BigDecimal;9
15 importjavax.servlet.http.HttpServletResponse;16
17 importorg.apache.poi.hssf.util.HSSFColor;18 importorg.apache.poi.ss.usermodel.Cell;19
importorg.apache.poi.ss.usermodel.CellStyle;20 importorg.apache.poi.ss.usermodel.Font;21
importorg.apache.poi.ss.usermodel.HorizontalAlignment;22 importorg.apache.poi.ss.usermodel.Row;23
importorg.apache.poi.ss.usermodel.Sheet;24 importorg.apache.poi.ss.usermodel.VerticalAlignment;25
importorg.apache.poi.ss.util.CellRangeAddress;26 importorg.apache.poi.xssf.streaming.SXSSFSheet;27
importorg.apache.poi.xssf.streaming.SXSSFWorkbook;28
web.page.Pager;30
31 public classExportExcle {32
33 /**最⼤导出⾏数*/
34 public static final int MAX_ROWS = 500000;35
36 /**分页⾏数*/
37 public static final int PAGING_ROWS = 50000;38
39 /**SXSSF操作⾏数*/
40 public static final int SXSSF_ROWS = 100;41
42 /**缓存⾏数*/
43 public static final int CACHE_ROWS = 1000;44
45 /**创建Workbook*/
46 SXSSFWorkbook workbook = newSXSSFWorkbook(SXSSF_ROWS);47
48 /**当前Sheet*/
49 Sheet sheet;50
51 /**内容总数*/
52 private int contentCount = 0;53
54 /**总页数*/
55 private intpageCount;56
57 /**分页列表*/
58 private List pagerList = new ArrayList<>();59
60 /**标题*/
61 privateString title;62
63 /**表头数组*/
64 privateObject[][] headerArray;65
66 /**导出列数*/
67 private intcolCount;68 /**标题⾏数*/
69 private int titleRows = 0;70 /**标题⾏数*/
71 private int headerRows = 0;72
73 /**样式Map*/
74 private Map styleMap = new HashMap<>();75
76 /**列宽数组*/
77 privateInteger[] intArray;78
79 /**构造⽅法*/
80 publicExportExcle() {81 }82 // //***Demo***83 //ExportExcle exportExcle = new ExportExcle();//新建导出对象84 //int contentCount = 0;//从数据库获取内容总数(可选)----------step_0(数据量⼤于50000,建议设置)85
//exportExcle.setContentCount(contentCount);//设置内容总数(可选)----------step_0(数据量⼤于50000,建议设置)86 //Object[] headerArray = new Object[] {//表头数组87 //"",88 //""};89 //exportExcle.setTitleAndHeader("标题", headerArray);//设置标题和表头----------step_190 // //遍历分页列表进⾏操作91 //for(Pager pager : PagerList()) {92 //List contentList = new ArrayLi
st<>();//内容列表93 // //---------- 将从数据库获取的数据封装成List开始94 //Paginater paginater =
server.findSplitPage(pager);95 //for(Object object : Data()) {96 //Map map = (Map) object;97 //Object[] objArr = new Object[] {};98 //contentList.add(objArr);//增加内容99 //}100 // //---------- 将从数据库获取的数据封装成List结束101
//exportExcle.setContentPagerDate(contentList, pager);//设置需要导出的内容列表----------step_2102 //}103
//portWorkbook(response);//将⽂件写⼊输出流----------step_3
104
105
106 /**step_0:设置内容总数(不设置则默认为单页导出)*/
107 public void setContentCount(intcontentCount) {tCount = contentCount; //设置内容总数
109 }110
111 /**step_1:设置标题和表头数组(单⾏),并初始化参数*/
112 public voidsetTitleAndHeader(String title, Object[] headerArray) {113 Object[][] headerArrayTemp = new Object[1] [];114 headerArrayTemp[0] =headerArray;115 setTitleAndHeader(title, headerArrayTemp);116 }117 /**step_1:设置标题和表头数组(多⾏),并初始化参数*/
118 public voidsetTitleAndHeader(String title, Object[][] headerArray) {119 this.title =title;120 this.headerArray
=headerArray;121 parameterChecking(); //校验参数
122 }123
124 /**step_2:设置需要导出的内容列表*/
125 public void setContentPagerDate(ListcontentList, Pager pager) {126 LogUtil.APP.info("开始将[" + title + "] - 第" + PageNumber() +"页数据写⼊Excle⽂件 - "
127 + CurrentDateTime("yyyy-MM-dd HH:mm:ss"));128 if(null == contentList ||contentList.isEmpty()) {129 throw new IllegalArgumentException("查询不到需要导出的数据[contentList]");130 }131 //---------- 导出数据到Excle⽂件Sheet页开始
132 String sheetName = "第" + PageNumber() +"页 - 共" + pageCount + "页"; //sheet名称
133 sheet = ateSheet(sheetName); //创建⼯作表
134 writeTitle(); //写⼊标题
135 writeHeader(); //写⼊表头数组
136 writeContent(contentList); //写⼊内容列表
137 autoColumnSize(); //⾃适应列宽,并冻结窗格138 //---------- 导出数据到Excle⽂件Sheet页结束
139 contentList.clear(); //清空列表
140 LogUtil.APP.info("将[" + title + "] - 第" + PageNumber() +"页数据写⼊Excle⽂件结束 - "
141 + CurrentDateTime("yyyy-MM-dd HH:mm:ss"));142 }143
144 /**step_3:将⽂件写⼊输出流*/
145 public voidexportWorkbook() {146 exportWorkbook("D:/"); //默认导出到D盘根⽬录
147 }148 /**step_3:将⽂件写⼊输出流*/
149 public voidexportWorkbook(String path) {150 FileOutputStream fos = null;151 try{152 fos = new
FileOutputStream(path + title + ".xlsx");153 workbook.write(fos);154 ((SXSSFWorkbook) workbook).dispose();155 }
catch(IOException e) {156 e.printStackTrace();157 } finally{158 if (fos != null) {159 try{160 fos.close();161 }
catch(IOException e) {162 e.printStackTrace();163 }164 }165 }166 }167 /**step_3:将⽂件写⼊输出流*/
168 public voidexportWorkbook(HttpServletResponse response) {169 ByteArrayOutputStream baos = null;170 OutputStream os = null;171 try{172 baos = newByteArrayOutputStream();173 workbook.write(baos);174 ((SXSSFWorkbook) workbook).dispose();175 String fileName = new Bytes("gbk"), "ISO8859-1");set(); //清空输出流
177 response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");178
response.setContentType("application/msexcel");179 response.setContentLength(baos.size());180 os
=OutputStream();181 baos.writeTo(os);182 os.flush();183 } catch(IOException e) {184 e.printStackTrace();185 } finally{186 if (baos != null) {187 try{188 baos.close();189 } catch(IOException e) {190 e.printStackTrace();191 }192 }193 if (os != null) {194 try{195 os.close();196 } catch(IOException e) {197 e.printStackTrace();198 }199 }200 }201 }202
203
204 //--------------------------------------------------调⽤的⽅法--------------------------------------------------
205
206
207 /**校验参数*/
208 private voidparameterChecking() {209 if(null ==title) {210 throw new IllegalArgumentException("标题未设置");211 }212 if(null == headerArray || headerArray.length == 0) {213 throw new IllegalArgumentException("表头数组未设置");214 }
else{215 if(null != headerArray[0] && 0 < headerArray[0].length) {216 headerRows = headerArray.length; //设置表头⾏数
217 colCount = headerArray[0].length; //设置导出列数
218 intArray = new Integer[colCount]; //初始化列宽数组
219 } else{220 throw new IllegalArgumentException("⽆法确定导出列数");221 }222 }223 if(contentCount <= 0) {224 contentCount = PAGING_ROWS; //默认为单页导出
225 }226 setPagerList(); //设置分页信息
227 initStyleMap(); //初始化样式Map
228 }229
230 /**设置分页列表*/
231 private voidsetPagerList() {232 if(contentCount >MAX_ROWS) {233 contentCount =MAX_ROWS;234 }235 //计算总页数
236 pageCount = contentCount % PAGING_ROWS > 0 ? contentCount / PAGING_ROWS + 1 : contentCount
/PAGING_ROWS;237 //设置分页列表
238 for (int i = 1; i <= pageCount; i++) {239 //int paging = i == pageCount && contentCount % PAGING_ROWS > 0 ?240 //contentCount % PAGING_ROWS : PAGING_ROWS;//当前分页⾏数241 //pagingList.add(i, new Pager(i, paging));
242 pagerList.add(newPager(i, PAGING_ROWS));243 }244 }245 /**获取分页列表*/
246 public ListgetPagerList() {247 returnpagerList;248 }249
250
251 //--------------------------------------------------Excle操作--------------------------------------------------
252
253
254 /**写⼊表头标题*/
255 private voidwriteTitle() {256 //创建⾏对象
257 Row row = ateRow(0); //创建⾏对象
258 Cell cell = ateCell(0); //创建单元格
259 cell.setCellValue(title); //写⼊内容
260 setRowStyle(0, ("titleStyle")); //设置⾏样式
261 mergedRegion(0, 0, 0, colCount-1); //合并单元格
262 titleRows = 1; //记录标题⾏数
263 }264
265 /**写⼊表头数组headerArray[row][col]*/
266 private voidwriteHeader() {267 for(int rowNum=0; rowNum < headerRows; rowNum++) {268 if(null ==
headerArray[rowNum] || 0 ==headerArray[rowNum].length) {269 continue; //⾏数据为空,跳出当次循环
270 }271 //创建⾏对象
272 Row row = ateRow(rowNum +titleRows);273 for(int colNum=0; colNum < colCount; colNum++) {274 Cell cell = ateCell(colNum); //创建单元格
275 cell.("headerStyle")); //设置表头样式
276 if(null == headerArray[rowNum][colNum] || "*".equals(headerArray[rowNum][colNum])) {277 continue; //单元格数据为空,跳出当次循环
278 }279 setCellValue(cell, headerArray[rowNum][colNum], colNum); //写⼊内容值
280 }281 }282 }283
284 /**写⼊内容列表contentList*/
285 private void writeContent(ListcontentList) {286 for(int rowNum = 0; rowNum < contentList.size();
rowNum++) {287 Object[] array =(rowNum);288 if(null == array || 0 ==array.length) {289 continue; //数组为空,跳出当次循环
290 }291 //创建⾏对象
292 Row row = ateRow(rowNum + titleRows + titleRows); //在表头之后
下载apache293 for(int colNum = 0; colNum < array.length; colNum++) {294 if(null ==array[colNum]) {295 continue; //跳出当次循环
296 }297 Cell cell = ateCell(colNum); //创建单元格
298 cell.("contentStyle")); //设置样式
299 setCellValue(cell, array[colNum], colNum); //写⼊内容值
300 }301 //每当⾏数达到设置的值就刷新数据到硬盘,以清理内存
302 if(rowNum % CACHE_ROWS == 0){303 try{304 ((SXSSFSheet) sheet).flushRows();305 } catch(IOException e) {306 e.printStackTrace();307 }308 }309 }310 autoMergedRegion(); //⾃动合并单元格
311 }312
313 /**⾃适应列宽*/
314 private voidautoColumnSize() {315 /*//⾃适应列宽316 for(int colNum=0; colNum
324 //批量设置列宽
325 for(int i=0; i
328 intArray[i] =DefaultColumnWidth();329 }330 sheet.setColumnWidth(i, (int)((intArray[i] + 2 + 0.72) * 256)); //参数为列index,列宽(字符数)
331 }332 //冻结窗格
ateFreezePane(0, titleRows + headerRows, 0, titleRows +headerRows);334 }335
336
337
338 /**设置单元格的值*/
339 private void setCellValue(Cell cell, Object obj, intcolNum) {340 //格式化参数
341 if(obj instanceof BigDecimal || obj instanceofDouble) {342 Double decimal = Double.String().replace(" ", ""));343 obj = new DecimalFormat("#0.00").format(decimal);344 }345 cell.String()); //写⼊内容
346 try{347 int length = String().getBytes("gbk").length;348 if(intArray[colNum] == null || intArray[colNum]
356 /**⾃动合并单元格*/
357 private voidautoMergedRegion() {358 if(null == headerArray || 0 ==headerArray.length) {359 return; //表头数组为空,退出⽅法
360 }361 if(null == headerArray[0][0]) {362 headerArray[0][0] = ""; //初始项不能空
363 }364 //设置表头数值
365 for(int rowNum=0; rowNum < headerRows; rowNum++) {366 for(int colNum=0; colNum < colCount; colNum++) {367 if(null != headerArray[rowNum][colNum] && !"*".equals(headerArray[rowN
um][colNum])) {368 autoMergedRegion(rowNum ,colNum); //执⾏合并操作
369 }370 }371 }372 }373 /**执⾏合并操作*/
374 private void autoMergedRegion(int firstRow ,intfirstCol) {375 int lastRow = headerRows - 1; //最后⼀⾏
376 int lastCol = colCount - 1; //最后⼀列377 //如果不为最后⼀⾏
378 if(firstRow !=lastRow) {379 for(int row = firstRow+1; row < headerRows; row++) {380 if(null !=headerArray[row] [firstCol]) {381 if("*".equals(headerArray[row][firstCol])) {382 lastRow = row; //定位最后⼀⾏,占位符不减1
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论