[Log] generate and download reports

The end of a busy pumping out of time. . .


Record the past few days to write the report generation and download it

Download the report of the front end

Reception using vue, using a method form of the form,
download there are several ways to feel this more in line with demand, uses this method

 <form name="DownLoad" id="DownLoad" method="post" enctype="application/x-www-form-urlencoded"
              style="display:none" target="downLoadIframe">
            <input type="text" name="userId" id="userId"/>
            <input type="text" name="date" id="date"/>
        </form>
        <iframe name="downLoadIframe" id="downLoadIframe" style="display:none">
        </iframe>

Passing parameters using input

Direct write requests in the action

 DownExcel() {
                var req = this.Base();
                var myForm = document.getElementById("DownLoad");
                if (this.value7.length != 0) {
                    let date = this.formatedDate(this.value7[0]) + ',' + this.formatedDate(this.value7[1])
                    document.getElementById("date").value = date;
                }
                document.getElementById("projectId").value = req.projectId;
                document.getElementById("userId").value = req.userId;
                let url = window.location.href;
                myForm.action = "请求.do";
          
                myForm.submit();
            },

Background report generation

Poi report generation using a
check from the database data is inserted into the table

// 生成报表
		public static String createExcel(String projectId, String tmpPath, ArrayList<Map> data) {

			// 表头
			ArrayList<String> titleRow = new ArrayList<String>();
			 
			// 表格数据
			ArrayList excelData = new ArrayList();
			for (int i = 0; i < data.size(); i++) {
				ArrayList<String> rowData = new ArrayList<String>();
				rowData.add(((Map) data.get(i)).get("name").toString());
				excelData.add(rowData);
			}

			// 表名
			Date nowDate = new Date(System.currentTimeMillis());
			SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
			String dateStr = sf.format(nowDate); // 文件名
			String fileName = dateStr + "-" + projectId + ".xls";
			String filePath = tmpPath + "/" + fileName; // Excel文件路径和文件名

			HSSFWorkbook workbook = new HSSFWorkbook();
			// 添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
			Sheet sheet1 = workbook.createSheet("sheet1");
			sheet1.setDefaultColumnWidth(20);
			// 新建文件
			FileOutputStream out = null;
			try {
				// 添加表头
				Row row = workbook.getSheet("sheet1").createRow(0); // 创建第一行
				for (int i = 0; i < titleRow.size(); i++) {
					Cell cell = row.createCell(i);
					cell.setCellValue(titleRow.get(i));
				}
				// 插入数据
				for (int i = 0; i < excelData.size(); i++) {
					Row rowData = workbook.getSheet("sheet1").createRow(i + 1);
					ArrayList rowArr = (ArrayList) excelData.get(i);
					for (int j = 0; j < rowArr.size(); j++) {
						Cell cell = rowData.createCell(j);
						cell.setCellValue(rowArr.get(j).toString());
					}
				}
				out = new FileOutputStream(filePath);
				workbook.write(out);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return filePath;   // 报表生成之后,将报表的路径返回
		}

 //将报表转换成 buffer 进行返回
	        byte[] buffer=null;
	        
	        try{
	            buffer = this.getFileBytes(filePath);
	        }catch (IOException e){
	            logger.error(e.getMessage());
	            throw new Exception("file download error");
	        }



// 更改响应头
 private String contentType = "application/x-download";
    private String fileNameField = "DownloadFileName"; 
    private String fileContentField = "DownloadFileContent";

    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType(getContentType());
        StringBuffer sb = new StringBuffer();
        sb.append("attachment; filename=");
        String fileName = URLEncoder.encode((String)model.get(this.fileNameField), "UTF-8");
        sb.append(fileName);
 
        response.setHeader("Content-Disposition", sb.toString());
        response.setContentType(contentType);
        if (this.log.isDebugEnabled())
            this.log.debug(sb.toString());
        try {
            ServletOutputStream sos = response.getOutputStream();
            byte[] arrayOfByte = (byte[]) model.get(this.fileContentField);
            sos.write(arrayOfByte);
            sos.flush();
        } catch (Exception exception) {
            this.log.error("render", exception);
        }
    }

Spring background use
this function to accomplish this, of course, we need to optimize the place


Although able to complete the entire front and back binding function,
advantages and disadvantages
so you can have the entire development process a certain understanding
result is that the depth of knowledge to master enough

About the depth of knowledge had to do their homework,
to complete the work matters

Guess you like

Origin blog.csdn.net/java_sparrow/article/details/85303674