欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2023/12/29 37 豆豆
生活随笔 收集整理的这篇文章主要介绍了 导出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:下载模板时填充数据方法实现的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。