Excel单页导出以及多sheet导出
生活随笔
收集整理的這篇文章主要介紹了
Excel单页导出以及多sheet导出
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
注意,我將一些方法抽出來放到文章末尾了,這幾個方法為:
desStyle,titleStyle,celStyle功能一.Excel單頁導出,即將所有的數據導入一個sheet頁
導出Excel的主方法,所需參數只需要有request和response即可,另外兩個是我為了查詢寫入Excel數據而加入的(一個是我的service,一個是我的實體類),使用時直接復制此方法即可。
另外,其中會有一些方法,諸如getFormatDate_ymd和toUTF8String等都是一些自己寫的格式數據格式的方法,這些方法取決于你的數據是否需要格式化,這些都無傷大雅,這幾個方法我也在下面列出來了。:
public static String meBespokeExportedEexecl(TsinghuaMeBespoke tsinghuaMeBespoke,HttpServletResponse response, HttpServletRequest request,TsinghuaMeBespokeService tsinghuaMeBespokeService) throws Exception {List<TsinghuaMeBespoke> tsinghuaMeBespokeList = tsinghuaMeBespokeService.findMyList(tsinghuaMeBespoke);HSSFWorkbook workBook = new HSSFWorkbook();ServletOutputStream out = null;String[] titles = {"序號", "姓名","性別", "身份證號","預約狀態", "預約日期", "預約時段","體檢套餐","套餐金額","實付金額","交費時間","學號","考試號","手機","院","系","生日"};CellStyle desStyle = workBook.createCellStyle();CellStyle titleStyle = workBook.createCellStyle();CellStyle celStyle = workBook.createCellStyle();titleStyle.setAlignment(CellStyle.ALIGN_CENTER);titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);CellStyle contentOddStyle = workBook.createCellStyle();contentOddStyle.setAlignment(CellStyle.ALIGN_CENTER);contentOddStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // contentOddStyle.setWrapText(true); // contentOddStyle.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);contentOddStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);contentOddStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);contentOddStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);contentOddStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);contentOddStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);CellStyle contentEvenStyle = workBook.createCellStyle();contentEvenStyle.setAlignment(CellStyle.ALIGN_CENTER);contentEvenStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // contentEvenStyle.setWrapText(true); // contentEvenStyle.setFillForegroundColor(HSSFColor.WHITE.index);contentEvenStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);contentEvenStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);contentEvenStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);contentEvenStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);contentEvenStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);HSSFSheet sheet = workBook.createSheet("**體檢人員預約信息表");Row desRow = sheet.createRow(0);// 合并單元格:參數:起始行, 終止行, 起始列, 終止列CellRangeAddress cra = new CellRangeAddress(0, 0, 0, (titles.length - 1));sheet.addMergedRegion(cra);//sheet.addMergedRegion(new Region(0, (short) 0, 0, titles.length > 0 ? (short) (titles.length - 1) : (short) 0));Cell descell = desRow.createCell(0);desRow.setHeight((short)900);descell.setCellValue("清華體檢人員預約信息表");descell.setCellStyle(desStyle(workBook, desStyle));try{// 標題信息Row titleRow = sheet.createRow(1);for (int i = 0; i < titles.length; i++) {Cell cell = titleRow.createCell(i);cell.setCellValue(titles[i]);cell.setCellStyle(titleStyle(workBook, titleStyle));titleRow.setHeight((short) 600);sheet.setColumnWidth(i, 7200);}Cell cell = null;for (int j = 0; j < tsinghuaMeBespokeList.size(); j++) {TsinghuaMeBespoke m = tsinghuaMeBespokeList.get(j);Row row = sheet.createRow(j + 2);row.setHeight((short) 300);//數據設置//人名String realnamed=m.getRealname();String realname;if(realnamed!=null && !"".equals(realnamed)){realname=realnamed;}else{realname=" ";}//性別String sex=m.getSex();if("1".equals(sex)){sex="男";}else if("2".equals(sex)){sex="女";}else{sex=" ";}//身份證號String identityCardd= m.getIdentityCard();String identityCard;if(identityCardd!=null && !"".equals(identityCardd)){identityCard=identityCardd;}else{identityCard="";}//預約狀態String bespokeStatus= m.getBespokeStatus();if("0".equals(bespokeStatus)){bespokeStatus="未預約";}else if("1".equals(bespokeStatus)){bespokeStatus="已預約";}else if("2".equals(bespokeStatus)){bespokeStatus="已報到";}else{bespokeStatus=" "; //未錄入}//預約日期Date bespokeDated= m.getBespokeDate();String bespokeDate="";if(bespokeDated!=null && !"".equals(bespokeDated)){bespokeDate=MyDateUtils.getFormatDate_ymd(bespokeDated);}//預約時段 開始String periodStartd=m.getPeriodStart();String periodStart="";if(periodStartd!=null && !"".equals(periodStartd)){periodStart=periodStartd;}//預約時段 結束String periodEndd=m.getPeriodEnd();String periodEnd="";if(periodEndd!=null && !"".equals(periodEndd)){periodEnd=periodEndd;}//預約時段String periodTime=periodStart+"-"+periodEnd;//體檢套餐String feescaleNamed=m.getFeescaleName();String feescaleName="";if(feescaleNamed!=null && !"".equals(feescaleNamed)){feescaleName=feescaleNamed;}//套餐金額Double feescaleMoneyd=m.getFeescaleMoney();String feescaleMoney="";if(feescaleMoneyd!=null && !"".equals(feescaleNamed)){feescaleMoney=feescaleMoneyd.toString();}//實付金額Double paymentMoneyd=m.getPaymentMoney();String paymentMoney="";if(paymentMoneyd!=null && !"".equals(paymentMoneyd)){paymentMoney=paymentMoneyd.toString();}//交費時間Date paymentDated= m.getPaymentTime();String paymentDate="";if(paymentDated!=null && !"".equals(paymentDated)){paymentDate=MyDateUtils.getFormatDate_ymd(paymentDated);}//學號String studentIdd=m.getStudentId();String studentId="";if(studentIdd!=null && !"".equals(studentIdd)){studentId=studentIdd;}//考試號 EXAMINE_NUMBERString examineNumberd=m.getExamineNumber();String examineNumber="";if(examineNumberd!=null && !"".equals(examineNumberd)){examineNumber=examineNumberd;}//手機String sjd=m.getSj();String sj="";if(sjd!=null && !"".equals(sjd)){sj=sjd;}//院String departmentd=m.getDepartment();String department="";if(departmentd!=null && !"".equals(departmentd)){department=departmentd;}//系String facultyd=m.getFaculty();String faculty="";if(facultyd!=null && !"".equals(facultyd)){faculty=facultyd;}//生日Date birthDated= m.getBirthDate();String birthDate="";if(birthDated!=null && !"".equals(birthDated)){birthDate=MyDateUtils.getFormatDate_ymd(birthDated);}String[] cellContents = {String.valueOf(j + 1),realname,sex,identityCard,bespokeStatus,bespokeDate,periodTime,feescaleName,feescaleMoney,paymentMoney,paymentDate,studentId,examineNumber,sj,department,faculty,birthDate};for (int i = 0; i < cellContents.length; i++) {String content = cellContents[i];cell = row.createCell(i);cell.setCellValue(content);cell.setCellStyle(celStyle(workBook, celStyle)); // cell.setCellStyle(j % 2 != 0 ? contentOddStyle : contentEvenStyle);}}// 文件名StringBuffer fileName = new StringBuffer("**體檢人員預約信息列表");fileName.append(MyDateUtils.getFormatDate(new Date()));fileName.append(".xls");response.setHeader("Content-disposition", "attachment;filename=" + toUTF8String(fileName.toString()));response.flushBuffer();out = response.getOutputStream();workBook.write(out);} catch (Exception e) {e.printStackTrace();} finally {try {out.flush();out.close();} catch (IOException e) {e.printStackTrace();}}return null;}幾個無傷大雅的格式化的方法:
public static String toUTF8String(String s) {StringBuffer sb = new StringBuffer();for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (c >= 0 && c <= 255) {sb.append(c);} else {byte[] b;try {b = Character.toString(c).getBytes(StandardCharsets.UTF_8);} catch (Exception ex) {System.out.println(ex);b = new byte[0];}for (int j = 0; j < b.length; j++) {int k = b[j];if (k < 0)k += 256;sb.append("%" + Integer.toHexString(k).toUpperCase());}}}return sb.toString();} public static String getFormatDate_ymd(Date date){String formatStr="";if(date!=null &&!"".equals(date)){formatStr = new SimpleDateFormat("yyyy-MM-dd").format(date);}return formatStr;}功能二.Excel導出數據為多個sheet頁
之所以會導出為多個sheet頁,是因為excel的單個sheet頁的容量是有限的,比如:
在Excel 2003中,每個工作表有65535行和256列,而在Excel 2007以上版本中,每個工作表有1048576行和16384列。
其實很簡單,我們只需要仔細調整一些循環條件即可,判斷新建sheet頁的情況就可以了,代碼如下,我就不再多贅述了,和上面的對比一下就能了解:
/*** 資費列表導出Excel* @param tsinghuaMeBespoke* @param response* @param request* @return* @throws Exception*/public static String meFeescaleExportedEexecl(TsinghuaMeBespoke tsinghuaMeBespoke,HttpServletResponse response, HttpServletRequest request,TsinghuaMeBespokeService tsinghuaMeBespokeService) throws Exception {List<TsinghuaMeBespoke> tsinghuaMeBespokeList = tsinghuaMeBespokeService.findFeeacleList(tsinghuaMeBespoke);HSSFWorkbook workBook = new HSSFWorkbook();ServletOutputStream out = null;String[] titles = {"序號", "姓名", "身份證號", "交費時間", "交費金額"};CellStyle desStyle = workBook.createCellStyle();CellStyle titleStyle = workBook.createCellStyle();CellStyle celStyle = workBook.createCellStyle();titleStyle.setAlignment(CellStyle.ALIGN_CENTER);titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);CellStyle contentOddStyle = workBook.createCellStyle();contentOddStyle.setAlignment(CellStyle.ALIGN_CENTER);contentOddStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // contentOddStyle.setWrapText(true); // contentOddStyle.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);contentOddStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);contentOddStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);contentOddStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);contentOddStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);contentOddStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);CellStyle contentEvenStyle = workBook.createCellStyle();contentEvenStyle.setAlignment(CellStyle.ALIGN_CENTER);contentEvenStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // contentEvenStyle.setWrapText(true); // contentEvenStyle.setFillForegroundColor(HSSFColor.WHITE.index);contentEvenStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);contentEvenStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);contentEvenStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);contentEvenStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);contentEvenStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);long sheetMax=0l;long rowEveP=3; //每頁的數據條數try{for (int sheetI = 0; sheetI< tsinghuaMeBespokeList.size(); sheetI++){if(sheetI%rowEveP==0){ //取余條件為每個分頁的數據條數HSSFSheet sheet = workBook.createSheet("清華體檢人員交費信息表<"+sheetMax+">");Row desRow = sheet.createRow(0);// 合并單元格:參數:起始行, 終止行, 起始列, 終止列CellRangeAddress cra = new CellRangeAddress(0, 0, 0, (titles.length - 1));sheet.addMergedRegion(cra);//sheet.addMergedRegion(new Region(0, (short) 0, 0, titles.length > 0 ? (short) (titles.length - 1) : (short) 0));Cell descell = desRow.createCell(0);desRow.setHeight((short)900);descell.setCellValue("**體檢人員交費信息表<"+sheetMax+">");descell.setCellStyle(desStyle(workBook, desStyle));// 標題信息Row titleRow = sheet.createRow(1);for (int i = 0; i < titles.length; i++) {Cell cell = titleRow.createCell(i);cell.setCellValue(titles[i]);cell.setCellStyle(titleStyle(workBook, titleStyle));titleRow.setHeight((short) 600);sheet.setColumnWidth(i, 7200);}Cell cell = null;for (int j = 0; j <rowEveP; j++) { // tsinghuaMeBespokeList.size() 此處設置每個分頁多少條數據//判斷是否超出數組容量if(sheetI+j<tsinghuaMeBespokeList.size()){TsinghuaMeBespoke m = tsinghuaMeBespokeList.get(sheetI+j); //j 每個分頁的每條數據Row row = sheet.createRow(j + 2);row.setHeight((short) 300);//日期格式化String paymentDate =MyDateUtils.getFormatDate_ymd(m.getPaymentTime());String[] cellContents = {String.valueOf(j + 1),m.getRealname(),m.getIdentityCard(),paymentDate,m.getPaymentMoney().toString()};for (int i = 0; i < cellContents.length; i++) {String content = cellContents[i];cell = row.createCell(i);cell.setCellValue(content);cell.setCellStyle(celStyle(workBook, celStyle));// cell.setCellStyle(j % 2 != 0 ? contentOddStyle : contentEvenStyle);}}}sheetMax++;}}/*原代碼塊位置*/// 文件名StringBuffer fileName = new StringBuffer("**體檢人員交費信息列表");fileName.append(MyDateUtils.getFormatDate(new Date()));fileName.append(".xls");response.setHeader("Content-disposition", "attachment;filename=" + toUTF8String(fileName.toString()));response.flushBuffer();out = response.getOutputStream();workBook.write(out);} catch (Exception e) {e.printStackTrace();} finally {try {out.flush();out.close();} catch (IOException e) {e.printStackTrace();}}return null;}大事兒,幾個抽出來的設置樣式的方法(要不然代碼太多不怎么好看)
//設置public static CellStyle desStyle(HSSFWorkbook wb, CellStyle ccellStyle) {ccellStyle.setAlignment(CellStyle.ALIGN_CENTER); // ccellStyle.setFillForegroundColor(HSSFColor.WHITE.index); // style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);ccellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);ccellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // ccellStyle.setWrapText(true);ccellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下邊框ccellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左邊框ccellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上邊框ccellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右邊框Font font = wb.createFont();font.setBoldweight(Font.BOLDWEIGHT_BOLD);//font.setColor(HSSFColor.BLACK.index);font.setFontHeight((short) 800);font.setFontHeightInPoints((short) 16);// 設置字體大小ccellStyle.setFont(font);return ccellStyle;}public static CellStyle titleStyle(HSSFWorkbook wb, CellStyle cellStyle) {cellStyle.setAlignment(CellStyle.ALIGN_CENTER);cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // cellStyle.setWrapText(true); // cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); // cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);Font font = wb.createFont();font.setBoldweight(Font.BOLDWEIGHT_BOLD); // font.setColor(HSSFColor.BLUE.index);cellStyle.setFont(font);cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下邊框cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左邊框cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上邊框cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右邊框 // cellStyle.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE); // cellStyle.setBorderLeft(HSSFCellStyle.BORDER_DOUBLE); // cellStyle.setBorderRight(HSSFCellStyle.BORDER_DOUBLE); // cellStyle.setBorderTop(HSSFCellStyle.BORDER_DOUBLE);return cellStyle;}public static CellStyle celStyle(HSSFWorkbook wb, CellStyle ccellStyle) {ccellStyle.setAlignment(CellStyle.ALIGN_CENTER); // ccellStyle.setFillForegroundColor(HSSFColor.WHITE.index); // style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);ccellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);ccellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // ccellStyle.setWrapText(true);ccellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下邊框ccellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左邊框ccellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上邊框ccellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右邊框Font font = wb.createFont(); // font.setBoldweight(Font.BOLDWEIGHT_BOLD);//font.setColor(HSSFColor.BLACK.index);font.setFontHeight((short) 1000);font.setFontHeightInPoints((short) 12);// 設置字體大小ccellStyle.setFont(font);return ccellStyle;}?
總結
以上是生活随笔為你收集整理的Excel单页导出以及多sheet导出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php dw文件上传下载,PHP-文件上
- 下一篇: 前端学习(2044)vue之电商管理系统