导出excel:下载模板时填充数据方法实现
生活随笔
收集整理的這篇文章主要介紹了
导出excel:下载模板时填充数据方法实现
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
| ?? ?/** ?? ? * 導(dǎo)出excel ?? ? * @param model ?? ? * @param request ?? ? * @param userAgent ?? ? * @param id ?? ? * @return ?? ? */ ?? ?@RequestMapping(value = "export.htm") ?? ?public void export(ModelMap model,HttpServletRequest request,HttpServletResponse response,UserAgent userAgent,@RequestParam(value = "taxpayerId",required = false) Integer id) { ?? ??? ?//獲取填充數(shù)據(jù) ?? ??? ?TaxpayerInfo selectByPrimaryKey = taxpayerInfoManager.selectByPrimaryKey(id); ?? ??? ?List<SupportOlder> supportOlderList=supportOlderManager.getListByTaxpayerId(id); ?? ??? ?//創(chuàng)建excel ?? ??? ?ExcelUtil excelUtil=new ExcelUtil(); ?? ??? ?//獲取模板存放路徑 ?? ??? ?String line=File.separator;? ?? ??? ?String realPath=request.getRealPath("")+"\\excelmodel\\"; ?? ??? ?System.out.println(realPath); ? ? ? ? //windows下 ? ? ? ? if("\\".equals(line)){ ? ? ? ? ?? ?realPath = realPath.replace("/", "\\"); ?// 將/換成\\ ? ? ? ? ?? ?realPath=realPath+line; ? ? ? ? } ? ? ? ?//linux下 ? ? ? ? if("/".equals(line)){ ? ? ? ? ?? ?realPath = realPath.replace("\\", "/"); ? ? ? ? ?? ?realPath=realPath+line; ? ? ? ? } ?? ??? ?String path=realPath+"supportOlder.xls"; ?? ??? ?String fileName="贍養(yǎng)老人支出明細(xì).xls"; ?? ??? ? ?? ??? ?//給excel設(shè)置模板、sheet名稱 ?? ??? ?excelUtil.setSrcPath(path); ?? ??? ?excelUtil.setSheetName("Sheet1"); ?? ??? ?excelUtil.getSheet(); ?? ??? ? ?? ??? ?//開始填充數(shù)據(jù) ?? ??? ?String cardType=""; ?? ??? ?cardType = getCardType(selectByPrimaryKey.getCardType()==null?"":selectByPrimaryKey.getCardType()); ?? ??? ?excelUtil.setCellStrValue(1, 1, cardType); ?? ??? ?excelUtil.setCellStrValue(1, 3, selectByPrimaryKey.getCardNo()); ?? ??? ?excelUtil.setCellStrValue(2, 1, selectByPrimaryKey.getName()); ?? ??? ?excelUtil.setCellStrValue(2, 3, selectByPrimaryKey.getIdentifyNo()); ?? ??? ?excelUtil.setCellStrValue(3, 1, selectByPrimaryKey.getWithholdingAgent()); ?? ??? ?excelUtil.setCellStrValue(3, 3, selectByPrimaryKey.getAgentNo()); ?? ??? ?int row=4; ?? ??? ?int col=-1; ?? ??? ?Integer num=0; ?? ??? ?for (SupportOlder supportOlder : supportOlderList) { ?? ??? ??? ?row++; ?? ??? ??? ?num++; ?? ??? ??? ?col=1; ?? ??? ??? ?excelUtil.setCellStrValue(row, 0, num.toString()); ?? ??? ??? ?excelUtil.setCellStrValue(row, col++, supportOlder.getName()); ?? ??? ??? ?excelUtil.setCellStrValue(row, col++, getCardType(supportOlder.getCardType())); ?? ??? ??? ?excelUtil.setCellStrValue(row, col++, supportOlder.getCardNo()); ?? ??? ?} ?? ??? ?//導(dǎo)出excel ?? ??? ?excelUtil.exportToWeb(response,fileName); ?? ??? ? ?? ?} |
工具類為ExcelUtil:
package com.zhiyuancorp.web.util;import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFWorkbook;import sun.misc.BASE64Decoder;import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse;import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Calendar; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;/*** * * @author baijf* @since 2015-9-19*/ public class ExcelUtil {private String srcXlsPath = "";// // 導(dǎo)入excel模板路徑private String desXlsPath = "";private String sheetName = "";POIFSFileSystem fs = null;HSSFWorkbook wb = null;HSSFSheet sheet = null;/*** 第一步、設(shè)置excel模板路徑* * @param srcXlsPath*/public void setSrcPath(String srcXlsPath) {this.srcXlsPath = srcXlsPath;}/*** 第二步、設(shè)置要生成excel文件路徑* * @param desXlsPath*/public void setDesPath(String desXlsPath) {this.desXlsPath = desXlsPath;}/*** 第三步、設(shè)置模板中哪個(gè)Sheet列* * @param sheetName*/public void setSheetName(String sheetName) {this.sheetName = sheetName;}/*** 第四步、獲取所讀取excel模板的對象*/public void getSheet() {try {File fi = new File(srcXlsPath);if (!fi.exists()) {System.out.println("模板文件:" + srcXlsPath + "不存在!");return;}fs = new POIFSFileSystem(new FileInputStream(fi));wb = new HSSFWorkbook(fs);sheet = wb.getSheet(sheetName);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}/*** 第五步、設(shè)置字符串類型的數(shù)據(jù)* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --字符串類型的數(shù)據(jù)*/public void setCellStrValue(int rowIndex, int cellnum, String value) {HSSFRow row = sheet.getRow(rowIndex);if (row == null) {row = sheet.createRow(rowIndex);}HSSFCell cell = row.getCell(cellnum);if (cell == null) {cell = row.createCell(cellnum);}cell.setCellValue(value);}/*** 第五步、設(shè)置日期/時(shí)間類型的數(shù)據(jù)* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --日期/時(shí)間類型的數(shù)據(jù)*/public void setCellDateValue(int rowIndex, int cellnum, Date value) {HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);cell.setCellValue(value);}/*** 第五步、設(shè)置浮點(diǎn)類型的數(shù)據(jù)* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --浮點(diǎn)類型的數(shù)據(jù)*/public void setCellDoubleValue(int rowIndex, int cellnum, double value) {HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);cell.setCellValue(value);}/*** 第五步、設(shè)置Bool類型的數(shù)據(jù)* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --Bool類型的數(shù)據(jù)*/public void setCellBoolValue(int rowIndex, int cellnum, boolean value) {HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);cell.setCellValue(value);}/*** 第五步、設(shè)置日歷類型的數(shù)據(jù)* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --日歷類型的數(shù)據(jù)*/public void setCellCalendarValue(int rowIndex, int cellnum, Calendar value) {HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);cell.setCellValue(value);}/*** 第五步、設(shè)置富文本字符串類型的數(shù)據(jù)。可以為同一個(gè)單元格內(nèi)的字符串的不同部分設(shè)置不同的字體、顏色、下劃線* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --富文本字符串類型的數(shù)據(jù)*/public void setCellRichTextStrValue(int rowIndex, int cellnum, RichTextString value) {HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);cell.setCellValue(value);}/*** 第六步、完成導(dǎo)出 type=0,不會修改表格名 type=1,修改表格名依次為當(dāng)日日期,明日日期,后天日期,遞增*/public void exportToWeb(HttpServletResponse response) {try {String encodedfileName = new String("預(yù)報(bào)準(zhǔn)確率統(tǒng)計(jì)".getBytes(), "ISO8859-1");response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + ".xls");response.setContentType("application/vnd.ms-excel");wb.write(response.getOutputStream());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** 第六步、完成導(dǎo)出 type=0,不會修改表格名 type=1,修改表格名依次為當(dāng)日日期,明日日期,后天日期,遞增*/public void exportToWeb(HttpServletResponse response, String fileName) {try {String encodedfileName="";if(fileName.toLowerCase().endsWith(".xls")){encodedfileName= new String(fileName.getBytes(), "ISO8859-1");}else{encodedfileName=new String(fileName.getBytes(), "ISO8859-1")+".xls";}response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");response.setContentType("application/vnd.ms-excel");wb.write(response.getOutputStream());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** 根據(jù)模版導(dǎo)出Excel(2007及以上版本)* @param response 響應(yīng)對象* @param tempFileName 模版文件名* @param outFileName 輸出文件名* @param sheetIndex Sheet頁簽索引,從0開始* @param startRow 開始行,從0開始* @param startCell 開始列,從0開始* @param dataList 數(shù)據(jù)集合,不能為空* @param images 圖片集合(可選)*/public static void exportExcelByTemp07 (HttpServletResponse response, String tempFileName, String outFileName, Integer sheetIndex, Integer startRow, Integer startCell, List<LinkedHashMap<String, Object>> dataList) {Workbook wb = null;InputStream is = null;try {is = new FileInputStream(getFilePath(tempFileName));// 第一步:創(chuàng)建工作空間,對應(yīng)Excel文件wb = new XSSFWorkbook(is);// 第二步:向工作工作空間中寫入內(nèi)容exportExcelByTemp(wb, sheetIndex, startRow, startCell, dataList);// 第三步:將文件輸出到客戶端瀏覽器outExcelToClient(response, wb, outFileName);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}}}private static String getFilePath (String fileName) throws UnsupportedEncodingException {String root = ExcelUtil.class.getResource("/").getPath();if (root.indexOf("target") >= 0) {root = root.substring(1, root.indexOf("target"));root = root.replaceAll("/", "\\\\");root = root + "src\\main\\webapp" + File.separator + "excle_model" + File.separator + fileName;} else {root = root.substring(1, root.indexOf("WEB-INF"));root = root.replaceAll("/", "\\\\");root = root + "excle_model" + File.separator + fileName;}return URLDecoder.decode(root, "GBK");}/*** 根據(jù)模版導(dǎo)出Excel* @param wb 工作空間,對應(yīng)Excel文件* @param sheetIndex Sheet頁簽索引,從0開始* @param startRow 開始行,從0開始* @param startCell 開始列,從0開始* @param dataList 數(shù)據(jù)集合,不能為空*/private static void exportExcelByTemp(Workbook wb, Integer sheetIndex, Integer startRow, Integer startCell, List<LinkedHashMap<String, Object>> dataList) {// Sheet頁簽,從0開始sheetIndex = (sheetIndex != null && sheetIndex > 0) ? sheetIndex : 0;// 第一步:獲取Sheet頁簽Sheet sheet = wb.getSheetAt(sheetIndex);// 如果頁簽不存在,則創(chuàng)建頁簽sheet = sheet != null ? sheet : wb.createSheet();if (dataList != null && dataList.size() > 0) {// 開始行startRow = (startRow != null && startRow > 0) ? startRow : 0;// 開始列startCell = (startCell != null && startCell > 0) ? startCell : 0;// 樣式(畫筆)CellStyle cellStyle = getStyle(wb);for (int i = 0, size = dataList.size(); i < size; i++) {// 第二步:獲取行// Row row = sheet.getRow(startRow + i);Row row = sheet.createRow(startRow + i);// 設(shè)置行高row.setHeightInPoints(20);LinkedHashMap<String, Object> dataMap = dataList.get(0);int j = 0;for (Map.Entry<String, Object> entry : dataMap.entrySet()) {// 第三步: 獲取單元格Cell cell = row.createCell(startCell + j);// Cell cell = row.getCell(startRow + j);// 設(shè)置單元格類型為字符串cell.setCellType(Cell.CELL_TYPE_STRING);cell.setCellValue(String.valueOf(entry.getValue()));cell.setCellStyle(cellStyle);j++;entry = null;}dataList.remove(0);}}}/*** 輸入Excel文件到客戶端* @param response 響應(yīng)對象* @param wb 工作空間,對應(yīng)一個(gè)Excel文件* @param fileName Excel文件名*/private static void outExcelToClient (HttpServletResponse response, Workbook wb, String fileName) {OutputStream out = null;try {response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));response.setContentType("application/vnd.ms-excel; charset=UTF-8");out = response.getOutputStream();wb.write(out);out.flush();} catch (IOException e) {e.printStackTrace();} finally {if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 獲取樣式* @param wb 工作空間* @return*/private static CellStyle getStyle(Workbook wb) {// 設(shè)置字體;Font font = wb.createFont();// 設(shè)置字體大小;font.setFontHeightInPoints((short) 12);// 設(shè)置字體名字;font.setFontName("Courier New");// font.setItalic(true); // 斜體// font.setStrikeout(true); // 刪除線// 設(shè)置樣式;CellStyle style = wb.createCellStyle();// 設(shè)置底邊框;style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 設(shè)置底邊框顏色;style.setBottomBorderColor(HSSFColor.BLACK.index);// 設(shè)置左邊框;style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 設(shè)置左邊框顏色;style.setLeftBorderColor(HSSFColor.BLACK.index);// 設(shè)置右邊框;style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 設(shè)置右邊框顏色;style.setRightBorderColor(HSSFColor.BLACK.index);// 設(shè)置頂邊框;style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 設(shè)置頂邊框顏色;style.setTopBorderColor(HSSFColor.BLACK.index);// 在樣式用應(yīng)用設(shè)置的字體;style.setFont(font);// 設(shè)置自動換行;style.setWrapText(false);// 設(shè)置水平對齊的樣式為居中對齊;style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 設(shè)置垂直對齊的樣式為居中對齊;style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);return style;}/*** 畫圖* @param wb 工作空間,對應(yīng)一個(gè)Excel文檔* @param image 圖片信息*/ /* private static void drawing (Workbook wb, Drawing drawing, Image image) {InputStream is = null;ByteArrayOutputStream os = null;try {//Base64解碼String base64 = image.getBase64().indexOf(",") >= 0 ? image.getBase64().split(",")[1] : image.getBase64();byte[] buffer = new BASE64Decoder().decodeBuffer(base64);is = new ByteArrayInputStream(buffer);// 將圖片寫入流中os = new ByteArrayOutputStream();BufferedImage bufferImg = ImageIO.read(is);// 利用Patriarch將圖片寫入ExcelImageIO.write(bufferImg, "PNG", os);// anchor主要用于設(shè)置圖片的屬性ClientAnchor anchor = null;if (wb instanceof HSSFWorkbook) {// Excel 03版本anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) image.getStartCell(), (short) image.getStartRow(), (short) (image.getWidth() + image.getStartCell()), (short) (image.getHeight() + image.getStartRow()));} else if (wb instanceof XSSFWorkbook) {// Excel 07版本及以上anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) image.getStartCell(), (short) image.getStartRow(), (short) (image.getWidth() + image.getStartCell()), (short) (image.getHeight() + image.getStartRow()));} else {throw new RuntimeException("工作空間(Workbook) 類型不匹配");}// 畫圖drawing.createPicture(anchor, wb.addPicture(os.toByteArray(), Workbook.PICTURE_TYPE_PNG));} catch (IOException e) {e.printStackTrace();} finally {if (os != null) {try {os.close();} catch (IOException e) {e.printStackTrace();}}if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}}}*/ }?
總結(jié)
以上是生活随笔為你收集整理的导出excel:下载模板时填充数据方法实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python与金融建模_【用Python
- 下一篇: 黑苹果macOS10.13安装记录