日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

导出excel:下载模板时填充数据方法实现

發布時間:2023/12/29 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 导出excel:下载模板时填充数据方法实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?? ?/**
?? ? * 導出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) {
?? ??? ?//獲取填充數據
?? ??? ?TaxpayerInfo selectByPrimaryKey = taxpayerInfoManager.selectByPrimaryKey(id);
?? ??? ?List<SupportOlder> supportOlderList=supportOlderManager.getListByTaxpayerId(id);
?? ??? ?//創建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="贍養老人支出明細.xls";
?? ??? ?
?? ??? ?//給excel設置模板、sheet名稱
?? ??? ?excelUtil.setSrcPath(path);
?? ??? ?excelUtil.setSheetName("Sheet1");
?? ??? ?excelUtil.getSheet();
?? ??? ?
?? ??? ?//開始填充數據
?? ??? ?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());
?? ??? ?}
?? ??? ?//導出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 = "";// // 導入excel模板路徑private String desXlsPath = "";private String sheetName = "";POIFSFileSystem fs = null;HSSFWorkbook wb = null;HSSFSheet sheet = null;/*** 第一步、設置excel模板路徑* * @param srcXlsPath*/public void setSrcPath(String srcXlsPath) {this.srcXlsPath = srcXlsPath;}/*** 第二步、設置要生成excel文件路徑* * @param desXlsPath*/public void setDesPath(String desXlsPath) {this.desXlsPath = desXlsPath;}/*** 第三步、設置模板中哪個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();}}/*** 第五步、設置字符串類型的數據* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --字符串類型的數據*/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);}/*** 第五步、設置日期/時間類型的數據* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --日期/時間類型的數據*/public void setCellDateValue(int rowIndex, int cellnum, Date value) {HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);cell.setCellValue(value);}/*** 第五步、設置浮點類型的數據* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --浮點類型的數據*/public void setCellDoubleValue(int rowIndex, int cellnum, double value) {HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);cell.setCellValue(value);}/*** 第五步、設置Bool類型的數據* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --Bool類型的數據*/public void setCellBoolValue(int rowIndex, int cellnum, boolean value) {HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);cell.setCellValue(value);}/*** 第五步、設置日歷類型的數據* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --日歷類型的數據*/public void setCellCalendarValue(int rowIndex, int cellnum, Calendar value) {HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);cell.setCellValue(value);}/*** 第五步、設置富文本字符串類型的數據??梢詾橥粋€單元格內的字符串的不同部分設置不同的字體、顏色、下劃線* * @param rowIndex* --行值* @param cellnum* --列值* @param value* --富文本字符串類型的數據*/public void setCellRichTextStrValue(int rowIndex, int cellnum, RichTextString value) {HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);cell.setCellValue(value);}/*** 第六步、完成導出 type=0,不會修改表格名 type=1,修改表格名依次為當日日期,明日日期,后天日期,遞增*/public void exportToWeb(HttpServletResponse response) {try {String encodedfileName = new String("預報準確率統計".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();}}/*** 第六步、完成導出 type=0,不會修改表格名 type=1,修改表格名依次為當日日期,明日日期,后天日期,遞增*/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();}}/*** 根據模版導出Excel(2007及以上版本)* @param response 響應對象* @param tempFileName 模版文件名* @param outFileName 輸出文件名* @param sheetIndex Sheet頁簽索引,從0開始* @param startRow 開始行,從0開始* @param startCell 開始列,從0開始* @param dataList 數據集合,不能為空* @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));// 第一步:創建工作空間,對應Excel文件wb = new XSSFWorkbook(is);// 第二步:向工作工作空間中寫入內容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");}/*** 根據模版導出Excel* @param wb 工作空間,對應Excel文件* @param sheetIndex Sheet頁簽索引,從0開始* @param startRow 開始行,從0開始* @param startCell 開始列,從0開始* @param dataList 數據集合,不能為空*/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);// 如果頁簽不存在,則創建頁簽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);// 設置行高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);// 設置單元格類型為字符串cell.setCellType(Cell.CELL_TYPE_STRING);cell.setCellValue(String.valueOf(entry.getValue()));cell.setCellStyle(cellStyle);j++;entry = null;}dataList.remove(0);}}}/*** 輸入Excel文件到客戶端* @param response 響應對象* @param wb 工作空間,對應一個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) {// 設置字體;Font font = wb.createFont();// 設置字體大小;font.setFontHeightInPoints((short) 12);// 設置字體名字;font.setFontName("Courier New");// font.setItalic(true); // 斜體// font.setStrikeout(true); // 刪除線// 設置樣式;CellStyle style = wb.createCellStyle();// 設置底邊框;style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 設置底邊框顏色;style.setBottomBorderColor(HSSFColor.BLACK.index);// 設置左邊框;style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 設置左邊框顏色;style.setLeftBorderColor(HSSFColor.BLACK.index);// 設置右邊框;style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 設置右邊框顏色;style.setRightBorderColor(HSSFColor.BLACK.index);// 設置頂邊框;style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 設置頂邊框顏色;style.setTopBorderColor(HSSFColor.BLACK.index);// 在樣式用應用設置的字體;style.setFont(font);// 設置自動換行;style.setWrapText(false);// 設置水平對齊的樣式為居中對齊;style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 設置垂直對齊的樣式為居中對齊;style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);return style;}/*** 畫圖* @param wb 工作空間,對應一個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主要用于設置圖片的屬性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();}}}}*/ }

?

總結

以上是生活随笔為你收集整理的导出excel:下载模板时填充数据方法实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。