PDF报表 项目实战总结(集成百度地图+遇到的问题)

PDF

在前面的课程中我们完成了将运营数据导出到Excel文件的功能。在企业开发中,除了常见的Excel形式
报表,还有PDF形式的报表。那么如何导出PDF形式的报表呢?

1. 常见的PDF报表生成方式

1.1 iText

iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText
不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。 iText的安装非常方便,
下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类
库了。
maven坐标:

<dependency>
 <groupId>com.lowagie</groupId>
  <artifactId>itext</artifactId>
   <version>2.1.7</version>
    </dependency>

示例代码

import com.lowagie.text.Document; 
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
public class ItextDemo { 
        public static void main(String[] args) { 
        try {Document document = new Document(); 
        PdfWriter.getInstance(document, new FileOutputStream("D:\\test.pdf")); 
        document.open(); 
        document.add(new Paragraph("hello itext")); 
        document.close();
         } catch (FileNotFoundException e) 
         { e.printStackTrace();
          } catch (DocumentException e) { e.printStackTrace(); 
          }
           } 
           }

1.2 JasperReports

maven

<dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.8.0</version>
        </dependency>

2. JasperReports概述

### 2.1 JasperReports快速体验
JRXML:报表填充模板,本质是一个xml文件
Jasper:由JRXML模板编译成的二进制文件,用于代码填充数据
Jrprint:当用数据填充完Jasper后生成的对象,用于输出报表

具体实现pdf

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.8.0</version>
        </dependency>

html

<!DOCTYPE html>
<html>
    <head>
        <!-- 页面meta -->
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>传智健康</title>
        <meta name="description" content="传智健康">
        <meta name="keywords" content="传智健康">
        <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
        <!-- 引入样式 -->
        <link rel="stylesheet" href="../plugins/elementui/index.css">
        <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
        <link rel="stylesheet" href="../css/style.css">
        <style>
            .grid-content {
                border-radius: 4px;
                min-height: 40px;
            }
        </style>
    </head>
    <body class="hold-transition">
        <div id="app">
            <div class="content-header">
                <h1>统计分析<small>运营数据</small></h1>
                <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>统计分析</el-breadcrumb-item>
                    <el-breadcrumb-item>运营数据</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="app-container">
                <div class="box" style="height: 900px">
                    <div class="excelTitle" >
                        <el-button @click="exportExcel">导出Excel</el-button>运营数据统计
                        <el-button @click="exportPDF">导出PDF</el-button>运营数据统计
                    </div>
                    <div class="excelTime">日期:{{reportData.reportDate}}</div>
                    <table class="exceTable" cellspacing="0" cellpadding="0">
                        <tr>
                            <td colspan="4" class="headBody">会员数据统计</td>
                        </tr>
                        <tr>
                            <td width='20%' class="tabletrBg">新增会员数</td>
                            <td width='30%'>{{reportData.todayNewMember}}</td>
                            <td width='20%' class="tabletrBg">总会员数</td>
                            <td width='30%'>{{reportData.totalMember}}</td>
                        </tr>
                        <tr>
                            <td class="tabletrBg">本周新增会员数</td>
                            <td>{{reportData.thisWeekNewMember}}</td>
                            <td class="tabletrBg">本月新增会员数</td>
                            <td>{{reportData.thisMonthNewMember}}</td>
                        </tr>
                        <tr>
                            <td colspan="4" class="headBody">预约到诊数据统计</td>
                        </tr>
                        <tr>
                            <td class="tabletrBg">今日预约数</td>
                            <td>{{reportData.todayOrderNumber}}</td>
                            <td class="tabletrBg">今日到诊数</td>
                            <td>{{reportData.todayVisitsNumber}}</td>
                        </tr>
                        <tr>
                            <td class="tabletrBg">本周预约数</td>
                            <td>{{reportData.thisWeekOrderNumber}}</td>
                            <td class="tabletrBg">本周到诊数</td>
                            <td>{{reportData.thisWeekVisitsNumber}}</td>
                        </tr>
                        <tr>
                            <td class="tabletrBg">本月预约数</td>
                            <td>{{reportData.thisMonthOrderNumber}}</td>
                            <td class="tabletrBg">本月到诊数</td>
                            <td>{{reportData.thisMonthVisitsNumber}}</td>
                        </tr>
                        <tr>
                            <td colspan="4" class="headBody">热门套餐</td>
                        </tr>
                        <tr class="tabletrBg textCenter">
                            <td>套餐名称</td>
                            <td>预约数量</td>
                            <td>占比</td>
                            <td>备注</td>
                        </tr>
                        <tr v-for="s in reportData.hotSetmeal">
                            <td>{{s.name}}</td>
                            <td>{{s.setmeal_count}}</td>
                            <td>{{s.proportion}}</td>
                            <td></td>
                        </tr>
                    </table>
                </div>
        </div>
    </body>
    <!-- 引入组件库 -->
    <script src="../js/vue.js"></script>
    <script src="../plugins/elementui/index.js"></script>
    <script type="text/javascript" src="../js/jquery.min.js"></script>
    <script src="../js/axios-0.18.0.js"></script>
    <script>
        var vue = new Vue({
            el: '#app',
            data:{
                reportData:{
                    reportDate:null,
                    todayNewMember :0,
                    totalMember :0,
                    thisWeekNewMember :0,
                    thisMonthNewMember :0,
                    todayOrderNumber :0,
                    todayVisitsNumber :0,
                    thisWeekOrderNumber :0,
                    thisWeekVisitsNumber :0,
                    thisMonthOrderNumber :0,
                    thisMonthVisitsNumber :0,
                    hotSetmeal :[
                        {name:'阳光爸妈升级肿瘤12项筛查(男女单人)体检套餐',setmeal_count:200,proportion:0.222},
                        {name:'阳光爸妈升级肿瘤12项筛查体检套餐',setmeal_count:200,proportion:0.222}
                    ]
                }
            },
            created() {
                axios.get("/report/getBusinessReportData.do").then((res)=>{
                    if (res.data.flag){
                        this.reportData = res.data.data;
                    }else {
                        this.$message.error(res.data.message);
                    }
                });
            },
            methods:{
                exportExcel(){
                    window.location.href = '/report/exportBusinessReport.do';
                },
                exportPDF(){
                    window.location.href = '/report/exportBusinessReport4PDF.do';
                }
            }
        })
    </script>
</html>

在这里插入图片描述

java

package com.ybb.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ybb.constant.MessageConstant;
import com.ybb.entity.Result;
import com.ybb.service.MemberService;
import com.ybb.service.ReportService;
import com.ybb.service.SetmealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Description :
 * Version :1.0
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request,HttpServletResponse response){
        try {
            Map<String, Object> data = reportService.getBusinessReportData();
            List<Map> hotSetmeal = (List<Map>) data.get("hotSetmeal");


            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";

            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, data, new JRBeanCollectionDataSource(hotSetmeal));
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");//pdf文件类型
            response.setHeader("content-Disposition","attachment;filename=report.pdf");//指定以附件下载
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
             out.flush();
            out.close();
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}

jrxml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.9.0.final using JasperReports Library version 6.9.0-cb8f9004be492ccc537180b49c026951f4220bf3  -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="health_business3" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="ae8a48ce-a368-40fb-b909-0f8fdc70db5a">
	<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
	<property name="com.jaspersoft.studio.data.sql.tables" value=""/>
	<parameter name="reportDate" class="java.lang.String"/>
	<parameter name="todayNewMember" class="java.lang.Integer"/>
	<parameter name="totalMember" class="java.lang.Integer"/>
	<parameter name="thisWeekNewMember" class="java.lang.Integer"/>
	<parameter name="thisMonthNewMember" class="java.lang.Integer"/>
	<parameter name="todayOrderNumber" class="java.lang.Integer"/>
	<parameter name="todayVisitsNumber" class="java.lang.Integer"/>
	<parameter name="thisWeekOrderNumber" class="java.lang.Integer"/>
	<parameter name="thisWeekVisitsNumber" class="java.lang.Integer"/>
	<parameter name="thisMonthOrderNumber" class="java.lang.Integer"/>
	<parameter name="thisMonthVisitsNumber" class="java.lang.Integer"/>
	<queryString>
		<![CDATA[]]>
	</queryString>
	<field name="name" class="java.lang.String"/>
	<field name="setmeal_count" class="java.lang.Long"/>
	<field name="proportion" class="java.math.BigDecimal"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="79" splitType="Stretch">
			<image>
				<reportElement x="0" y="0" width="130" height="60" uuid="cedbff82-d97a-47ad-ba89-27a4b08e0200"/>
				<imageExpression><![CDATA["http://www.itcast.cn/2018czgw/images/logo.png"]]></imageExpression>
			</image>
		</band>
	</title>
	<columnHeader>
		<band height="333" splitType="Stretch">
			<staticText>
				<reportElement x="80" y="3" width="400" height="40" uuid="f98ae3ef-08f2-472a-bccb-d1e7a3a0818a"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体" size="26" isBold="true"/>
				</textElement>
				<text><![CDATA[运营数据统计]]></text>
			</staticText>
			<staticText>
				<reportElement x="80" y="43" width="100" height="20" uuid="14097961-d148-428d-87f2-72af778a84c6">
					<property name="com.jaspersoft.studio.unit.leftIndent" value="pixel"/>
				</reportElement>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[日期]]></text>
			</staticText>
			<textField>
				<reportElement x="180" y="43" width="300" height="20" uuid="ef1af461-3c2f-4b73-9ecd-09f7535e92ec"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<textFieldExpression><![CDATA[$P{reportDate}]]></textFieldExpression>
			</textField>
			<staticText>
				<reportElement x="80" y="63" width="400" height="30" uuid="f37f902e-fb6b-434d-8d90-1d42f8704047"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体" size="16" isBold="true"/>
				</textElement>
				<text><![CDATA[会员数据]]></text>
			</staticText>
			<staticText>
				<reportElement x="80" y="93" width="100" height="30" uuid="ef4d70b9-155b-4c1d-aa70-03efea56f90d"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[今日新增会员数]]></text>
			</staticText>
			<textField>
				<reportElement x="180" y="93" width="100" height="30" uuid="618682c3-3f8b-46ca-adc7-f7423ed437e9"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<textFieldExpression><![CDATA[$P{todayNewMember}]]></textFieldExpression>
			</textField>
			<staticText>
				<reportElement x="280" y="93" width="100" height="30" uuid="65e62d93-4cae-4bc6-8ee3-4d4d2d61e781"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[总会员数]]></text>
			</staticText>
			<textField>
				<reportElement x="380" y="93" width="100" height="30" uuid="7f5177f3-9502-41a5-95a7-ec4df6063d66"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<textFieldExpression><![CDATA[$P{totalMember}]]></textFieldExpression>
			</textField>
			<staticText>
				<reportElement x="80" y="123" width="100" height="30" uuid="f55da761-1327-4c25-b37f-34dd5cbb376a"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[本周新增会员数]]></text>
			</staticText>
			<staticText>
				<reportElement x="280" y="123" width="100" height="30" uuid="a2710877-bf18-49a8-94c4-8589ee8ed772"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[本月新增会员数]]></text>
			</staticText>
			<textField>
				<reportElement x="180" y="123" width="100" height="30" uuid="70261e6e-2e79-4e75-8b0b-ef55edf224d2"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<textFieldExpression><![CDATA[$P{thisWeekNewMember}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="380" y="123" width="100" height="30" uuid="4c3f00b6-1ea9-46a5-95cd-154e36646cc3"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<textFieldExpression><![CDATA[$P{thisMonthNewMember}]]></textFieldExpression>
			</textField>
			<staticText>
				<reportElement x="80" y="153" width="400" height="30" uuid="6a0368a8-9abf-41c3-a7da-b723efa8001e"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体" size="16" isBold="true"/>
				</textElement>
				<text><![CDATA[预约到诊数据]]></text>
			</staticText>
			<staticText>
				<reportElement x="80" y="183" width="100" height="30" uuid="02f58de1-b014-40f3-a2de-fd27a1524931"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[今日预约数]]></text>
			</staticText>
			<staticText>
				<reportElement x="80" y="213" width="100" height="30" uuid="f890e926-6905-4d52-bfad-7b1fe1a2e818"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[本周预约数]]></text>
			</staticText>
			<staticText>
				<reportElement x="280" y="183" width="100" height="30" uuid="32d3a33c-6f19-4088-a0ce-dafaad05f124"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[今日到诊数]]></text>
			</staticText>
			<staticText>
				<reportElement x="280" y="213" width="100" height="30" uuid="a5ef305f-324b-4462-85ba-aca99079d5a1"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[本周到诊数]]></text>
			</staticText>
			<staticText>
				<reportElement x="80" y="243" width="100" height="30" uuid="a0ed3712-50c4-4ec4-89e3-af9487c36192"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[本月预约数]]></text>
			</staticText>
			<staticText>
				<reportElement x="280" y="243" width="100" height="30" uuid="971619ac-be81-4bc3-a4cc-b52b4e3472a4"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[本月到诊数]]></text>
			</staticText>
			<textField>
				<reportElement x="180" y="183" width="100" height="30" uuid="34565e63-ba1e-4071-82c2-ee43b0499a1d"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<textFieldExpression><![CDATA[$P{todayOrderNumber}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="380" y="183" width="100" height="30" uuid="ae02c431-a31c-489b-a5c6-4c9593b83fab"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<textFieldExpression><![CDATA[$P{todayVisitsNumber}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="180" y="213" width="100" height="30" uuid="87de624e-9780-4271-b6ef-8eff5f772237"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<textFieldExpression><![CDATA[$P{thisWeekOrderNumber}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="380" y="213" width="100" height="30" uuid="7b4d1fee-9ef4-4eb3-b3b2-92ecb984d0e9"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<textFieldExpression><![CDATA[$P{thisWeekVisitsNumber}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="180" y="243" width="100" height="30" uuid="bce46f32-693a-4b41-b18a-59311971aade"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<textFieldExpression><![CDATA[$P{thisMonthOrderNumber}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="380" y="243" width="100" height="30" uuid="2255e34e-4156-4ea8-a68b-3fe4c1a4b5d4"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<textFieldExpression><![CDATA[$P{thisMonthVisitsNumber}]]></textFieldExpression>
			</textField>
			<staticText>
				<reportElement x="80" y="273" width="400" height="30" uuid="1f5c4e29-66b3-4826-979a-d9e9de8d2878"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体" size="16" isBold="true"/>
				</textElement>
				<text><![CDATA[热门套餐]]></text>
			</staticText>
			<staticText>
				<reportElement x="80" y="303" width="140" height="30" uuid="24bb6d9b-fc02-4a7b-9b1d-bedbe656bf94"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[套餐名称]]></text>
			</staticText>
			<staticText>
				<reportElement x="220" y="303" width="130" height="30" uuid="f9d979b0-b369-4b8e-bf8c-9afcd15247e8"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[预约数量]]></text>
			</staticText>
			<staticText>
				<reportElement x="350" y="303" width="130" height="30" uuid="ea0738d2-8529-47f9-8605-d4af17aba0c7"/>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体"/>
				</textElement>
				<text><![CDATA[占比]]></text>
			</staticText>
		</band>
	</columnHeader>
	<detail>
		<band height="30" splitType="Stretch">
			<textField>
				<reportElement x="80" y="0" width="140" height="30" uuid="65dccdcd-434b-4a9e-8906-2aa06b3f3872">
					<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="f4b799cd-4b09-4a75-9829-c965580941f3"/>
				</reportElement>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体" size="10"/>
				</textElement>
				<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="220" y="0" width="130" height="30" uuid="e473e973-34a6-4caa-9c2c-883726ef9766">
					<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="5ff8329c-ae81-4468-a5a9-6a18406d0224"/>
				</reportElement>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体" size="10"/>
				</textElement>
				<textFieldExpression><![CDATA[$F{setmeal_count}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="350" y="0" width="130" height="30" uuid="beb087df-a4cf-47cb-ae00-792ac9b2829a">
					<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="1e2265d3-40ca-4e79-8311-7ab4f11fd914"/>
				</reportElement>
				<box>
					<pen lineWidth="0.5"/>
				</box>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font fontName="华文宋体" size="10"/>
				</textElement>
				<textFieldExpression><![CDATA[$F{proportion}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
</jasperReport>

fonts.xml

<?xml version="1.0" encoding="UTF-8"?>
<fontFamilies>
    <fontFamily name="华文宋体">
        <normal>stsong/stsong.ttf</normal>
        <bold>stsong/stsong.ttf</bold>
        <italic>stsong/stsong.ttf</italic>
        <boldItalic>stsong/stsong.ttf</boldItalic>
        <pdfEncoding>Identity-H</pdfEncoding>
        <pdfEmbedded>true</pdfEmbedded>
        <exportFonts>
            <export key="net.sf.jasperreports.html">'华文宋体',Arial,Helvetica,sans-serif</export>
            <export key="net.sf.jasperreports.xhtml">'华文宋体',Arial,Helvetica,sans-serif</export>
        </exportFonts>
    </fontFamily>
</fontFamilies>

stsong.ttf

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus adipisci aliquam, animi aspernatur blanditiis consequatur consequuntur deserunt distinctio dolorem earum eligendi error eveniet excepturi, facere incidunt itaque labore nemo nesciunt nostrum numquam perspiciatis quas quod recusandae suscipit tenetur ullam voluptate, voluptates. Ab deserunt eligendi fugiat libero minus, molestias obcaecati quibusdam.

项目实战

体检机构地址管理

在这里插入图片描述
自行建表,机构地址和预约表关联,设置字段(id,名称,电话号,经度,纬度,具体地址,图片)

在这里插入图片描述
在这里插入图片描述
新增:点击设置定位,弹出地图了文本框,把文本框和详细地址做一个数据绑定,但因为地图这个东西和vue不兼容,这里是用jq做的一个数据绑定,当设置具体地址时也赋值给上面。点击显示,用display会更好些,这样不会先占着空间不显示了
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

map.html

<!DOCTYPE html>
<html>
<head>
    <!-- 页面meta -->


    <title>地图</title>


    <!-- 引入样式 -->
    <link rel="stylesheet" href="../plugins/elementui/index.css">
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min(1).css">
    <link rel="stylesheet" href="../css/style.css">


    <meta http-equiv="Content-Type" content="text/html; charset=utf8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>批量地址</title>
    <style type="text/css">
        body, html{width: 100%;height: 100%;margin:0;font-family:"微软雅黑";}
        #l-map{height:500px;width:100%;}
        #r-result{width:100%; font-size:14px;line-height:20px;}
    </style>

    <script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=KDGv46KEciPKMHsimMUoTrPHfulDBksD"></script>





</head>





<body>

<div id="app">

<div id="l-map"></div>
<div id="r-result">
    <input type="button" value="点击查询预约诊所" onclick="bdGEO()"  />
    <div id="result"></div>
</div>

</div>
</body>
<!-- 引入组件库 -->
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>




<script type="text/javascript">
    // 百度地图API功能
    var map = new BMap.Map("l-map");
    map.centerAndZoom(new BMap.Point(121.55295,29.874135), 13);
    map.enableScrollWheelZoom(true);
    var index = 0;
    var myGeo = new BMap.Geocoder();
    var adds = [

    ];
    function bdGEO(){
        if (index < adds.length) {
            var add = adds[index];
            geocodeSearch(add);
            index++;
        }
    }
    function geocodeSearch(add){
        if(index < adds.length){
            setTimeout(window.bdGEO,400);
        }
        myGeo.getPoint(add, function(point){
            if (point) {
                document.getElementById("result").innerHTML +=  index + "、" + add + ":" + point.lng + "," + point.lat + "</br>";
                var address = new BMap.Point(point.lng, point.lat);
                addMarker(address,new BMap.Label(index+":"+add,{offset:new BMap.Size(20,-10)}));
            }
        }, "宁波市");
    }
    // 编写自定义函数,创建标注
    function addMarker(point,label){
        var marker = new BMap.Marker(point);
        map.addOverlay(marker);
        marker.setLabel(label);
    }

    $(document).ready(function () {
            $.ajax({url:"/map/findAllmap.do",success:function(result) {
                    adds =result;
                    /*bdGEO();*/
                },

        });
    });


</script>
</html>

address.html

<!DOCTYPE html>
<html xmlns:border="http://www.w3.org/1999/xhtml" xmlns: xmlns:display="http://www.w3.org/1999/xhtml" xmlns:
      xmlns:width="http://www.w3.org/1999/xhtml">
<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <title>传智健康</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../plugins/elementui/index.css">
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min(1).css">
    <link rel="stylesheet" href="../css/style.css">
    <!-- 引入组件库 -->
    <script type="text/javascript" src="../js/jquery.min.js"></script>
    <script src="../js/vue.js"></script>
    <script src="../plugins/elementui/index.js"></script>
    <script src="../js/axios-0.18.0.js"></script>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <style type="text/css">
        body, html {
            width: 100%;
            height: 100%;
            margin: 0;
            font-family: "微软雅黑";
            font-size: 14px;
        }

        #l-map {
            height: 500px;
            width: 100%;
        }

        #map2 {
            height: 500px;
            width: 100%;
        }

        #r-result {
            width: 100%;
        }

        #r-result2 {
            width: 100%;
        }
    </style>

    <script type="text/javascript"
            src="http://api.map.baidu.com/api?v=2.0&ak=KDGv46KEciPKMHsimMUoTrPHfulDBksD"></script>

    <style>
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }

        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .datatable {
            position: relative;
            box-sizing: border-box;
            -webkit-box-flex: 1;
            width: 100%;
            max-width: 100%;
            font-size: 14px;
            color: rgb(96, 98, 102);
            overflow: hidden;
            flex: 1 1 0%;
        }

        .datatable td, .datatable th {
            padding: 12px 0;
            min-width: 0;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            text-overflow: ellipsis;
            vertical-align: middle;
            position: relative;
            text-align: left;
        }

        #allmap {
            height: 450px;
            width: 100%;
            overflow: hidden;
            font-family: "微软雅黑";
            border: 1px solid green;
        }

        /*百度地图搜索框定位*/
        .tangram-suggestion-main {
            z-index: 999999;
        }

        /*设置弹出框样式*/
        .el-dialog__body {
            padding: 0px 20px;
            color: #606266;
            font-size: 14px;
        }

        /**/
        /*.el-input--suffix .el-input__inner {
            width: 450px;
        }*/
    </style>
</head>
<body class="hold-transition">
<div id="app">
    <div class="content-header">
        <h1>首页<small>公司分布图</small></h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>公司分布图</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <div class="app-container">
        <template>
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="分布图" name="first">
                    <iframe name="right" class="el-main" src="../pages/map.html" width="100%" height="580px"
                            frameborder="0"></iframe>
                </el-tab-pane>

                <el-tab-pane label="详细信息" name="second">
                    <div class="filter-container">
                        <el-input placeholder="公司地址" v-model="pagination.queryString" style="width: 200px;"
                                  class="filter-item" @keyup.enter.native="handleFilter"></el-input>
                        <el-button @click="findPage()" class="dalfBut">查询</el-button>
                        <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
                    </div>
                    <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
                        <el-table-column type="index" align="center" label="序号"></el-table-column>
                        <el-table-column prop="name" label="公司名称" align="center"></el-table-column>
                        <el-table-column prop="address" label="公司地址" align="center"></el-table-column>

                        <el-table-column prop="longitude" label="所在经度" align="center"></el-table-column>
                        <el-table-column prop="latitude" label="所在纬度" align="center"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                                <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination-container">
                        <el-pagination
                                class="pagiantion"
                                @current-change="handleCurrentChange"
                                :current-page="pagination.currentPage"
                                :page-size="pagination.pageSize"
                                layout="total, prev, pager, next, jumper"
                                :total="pagination.total">
                        </el-pagination>
                    </div>
                    <!-- 新增标签弹层 -->
                    <span class="add-form">
                        <el-dialog title="新增地址" :visible.sync="dialogFormVisible" @opened="createMap1">
                            <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right"
                                     label-width="100px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="体检机构名称" prop="name">
                                            <el-input v-model="formData.name"/>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="体检机构电话" prop="telephone">
                                            <el-input v-model="formData.telephone"/>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="上传图片">
                                            <el-upload
                                                    class="avatar-uploader"
                                                    action="/map/upload.do"
                                                    :auto-upload="autoUpload"
                                                    name="imgFile"
                                                    :show-file-list="false"
                                                    :on-success="handleAvatarSuccesss"
                                                    :before-upload="beforeAvatarUpload">
                                                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                            </el-upload>
                                        </el-form-item>
                                    </el-col>
                                </el-row>


                                <el-row>
                                    <el-col :span="8">
                                        <el-form-item label="经度" prop="longitude">
                                            <el-input v-model="formData.longitude" id="lng"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="纬度" prop="latitude">
                                            <el-input v-model="formData.latitude" id="lat"/>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="详细地址" prop="address">
                                            <el-input v-model="formData.address" id="txt"/>

                                        </el-form-item>

                                    </el-col>
                                       <el-button type="primary" icon="el-icon-search" @click="findditu1">设置定位</el-button>
                                </el-row>


                    <span id="r-result">
                        <input type="text" id="suggestId" size="20"
                                               style="width:300px;height:30px;display: none" placeholder="请输入地址" /> </span>

                                <div id="searchResultPanel"
                                     style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
                                <div id="l-map" style="display: none"></div>


                                </el-form-item>
                                </el-col>
                                </el-row>
                            </el-form>
                            <div slot="footer" class="dialog-footer">
                                <el-button @click="dialogFormVisible = false">取消</el-button>
                                <el-button type="primary" @click="handleAdd()">确定</el-button>
                            </div>
                        </el-dialog>
                    </div>


                    <!-- 编辑标签弹层 -->
                    <div class="add-form">
                        <el-dialog title="新增地址" :visible.sync="dialogFormVisible4Edit" @opened="createMap2">
                            <el-form ref="dataAddForm" :model="tableData" :rules="rules" label-position="right"
                                     label-width="100px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="体检机构名称" prop="name">
                                            <el-input v-model="formData.name"/>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="体检机构电话" prop="telephone">
                                            <el-input v-model="formData.telephone"/>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="上传图片">
                                            <el-upload
                                                    class="avatar-uploader"
                                                    action="/map/upload.do"
                                                    :auto-upload="autoUpload"
                                                    name="imgFile"
                                                    :show-file-list="false"
                                                    :on-success="handleAvatarSuccesss"
                                                    :before-upload="beforeAvatarUpload">
                                                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                            </el-upload>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="8">
                                        <el-form-item label="经度" prop="longitude">
                                            <el-input v-model="formData.longitude" id="lng"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="纬度" prop="latitude">
                                            <el-input v-model="formData.latitude" id="lat"/>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="详细地址" prop="address">
                                            <el-input v-model="formData.address" id="txt"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-button type="primary" icon="el-icon-search" @click="findditu2">设置定位</el-button>
                                </el-row>

                                <div id="r-result2"><input type="text" id="suggestId2" size="20"
                                                           style="width:300px;height:30px;display: none" placeholder="请输入地址"/>

                                </div>
                                <div id="searchResultPanel2"
                                     style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
                                <div id="map2" style="display: none"></div>

                            </el-form>
                            <div slot="footer" class="dialog-footer">
                                <el-button @click="dialogFormVisible = false">取消</el-button>
                                <el-button type="primary" @click="handleAdd()">确定</el-button>
                            </div>
                        </el-dialog>
                    </div>

                </el-tab-pane>
            </el-tabs>
        </template>
    </div>
</div>


</body>

<script>
    let vue = new Vue({
        el: '#app',
        data: {
            autoUpload: true,//自动上传
            imageUrl: null,//模型数据,用于上传图片完成后图片预览

            activeName: 'first',
            pagination: {//分页相关属性
                currentPage: 1,
                pageSize: 10,
                total: 100,
                queryString: null,
            },

            dataList: [],//列表数据
            formData: {},//表单数据
            tableData: {},//新增和编辑表单中对应的检查项列表数据
            dialogFormVisible: false,//控制添加窗口显示/隐藏
            dialogFormVisible4Edit: false,//控制编辑窗口显示/隐藏
            address_detail: '', //详细地址
            userlocation: {lng: "", lat: ""}
        },
        created() {
            this.findPage();
        },
        methods: {
            createMap1() {
                var marker;
                var zoomSize = 18;
                var map = new BMap.Map("l-map");
                var lon = 121.522812;  //默认为宁波市
                var lat = 29.92257;


                //业务处理,获取业务中的经纬度,有则处理,没有则用默认北京
                if (typeof getBizPoint == "function") {
                    var pointJson = getBizPoint();
                    lon = pointJson.lon;
                    lat = pointJson.lat;
                }

                //确定中心位置
                var point = new BMap.Point(lon, lat);
                map.centerAndZoom(point, zoomSize);


                //标注
                marker = new BMap.Marker(point);// 创建标注
                map.addOverlay(marker);             // 将标注添加到地图中
                marker.enableDragging();           // 可拖拽
                marker.addEventListener("dragend", setBizValue);

                // 添加带有定位的导航控件
                var navigationControl = new BMap.NavigationControl({
                    // 靠左上角位置
                    anchor: BMAP_ANCHOR_TOP_LEFT,
                    // LARGE类型
                    type: BMAP_NAVIGATION_CONTROL_LARGE,
                    // 启用显示定位
                    enableGeolocation: true
                });
                map.addControl(navigationControl);

                var geoc = new BMap.Geocoder();


                //输入地址事件处理 start
                var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
                    {
                        "input": "suggestId"
                        , "location": map
                    });

                ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
                    var str = "";
                    var _value = e.fromitem.value;
                    var value = "";
                    if (e.fromitem.index > -1) {
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

                    value = "";
                    if (e.toitem.index > -1) {
                        _value = e.toitem.value;
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
                    G("searchResultPanel").innerHTML = str;
                });

                var myValue;
                ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
                    var _value = e.item.value;
                    myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                    G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

                    let v3 = document.getElementById("txt");
                    v3.value = myValue;
                    v3.dispatchEvent(new Event('input'))

                    setPlace();
                });

                function setPlace() {
                    map.clearOverlays();    //清除地图上所有覆盖物
                    function myFun() {
                        var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                        setBizValueForPoint(pp);
                        map.centerAndZoom(pp, zoomSize);
                        marker = new BMap.Marker(pp);
                        marker.enableDragging();           // 可拖拽
                        map.addOverlay(marker);    //添加标注
                        marker.addEventListener("dragend", setBizValue);
                    }

                    var local = new BMap.LocalSearch(map, { //智能搜索
                        onSearchComplete: myFun
                    });
                    local.search(myValue);
                }

                function G(id) {
                    return document.getElementById(id);
                }

                //输入地址事件处理 end


                //地址转坐标
                function addrSearch(serachAddr) {
                    // 创建地址解析器实例
                    var myGeo = new BMap.Geocoder();
                    // 将地址解析结果显示在地图上,并调整地图视野
                    if (!serachAddr) {
                        serachAddr = $("#suggestId").val();
                    }
                    myGeo.getPoint(serachAddr, function (point) {
                        if (point) {
                            setBizValueForPoint(point);
                            map.clearOverlays();
                            map.centerAndZoom(point, zoomSize);
                            marker = new BMap.Marker(point);
                            marker.enableDragging();           // 可拖拽
                            map.addOverlay(marker);    //添加标注
                            marker.addEventListener("dragend", setBizValue);
                        } else {
                            console.log("search click no results!")
                        }
                    });
                }

                //业务方法 start
                //根据事件,设置经纬度和地址
                function setBizValue(e) {
                    var point = e.point;
                    setBizValueForPoint(point);
                }

                //根据Point,设置经纬度和地址
                function setBizValueForPoint(point) {
                    lon = point.lng;
                    lat = point.lat;

                    geoc.getLocation(point, function (rs) {
                        var addComp = rs.addressComponents;
                        addr = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                        if (typeof setBizFun == "function") {
                            setBizFun({lon: lon, lat: lat, addr: addr});
                        }
                    });

                    let v1 = document.getElementById("lng");
                    v1.value = lon;
                    v1.dispatchEvent(new Event('input'))

                    let v2 = document.getElementById("lat");
                    v2.value = lat;
                    v2.dispatchEvent(new Event('input'))

                }

                //根据marker,设置经纬度和地址
                function setBizValueForMarker() {
                    var point = marker.getPosition();
                    setBizValueForPoint(point);
                }
            },
            createMap2() {
                var marker;
                var zoomSize = 18;
                var map = new BMap.Map("map2");
                var lon = this.formData.longitude;  //默认为宁波市
                var lat = this.formData.latitude;

                //业务处理,获取业务中的经纬度,有则处理,没有则用默认北京
                if (typeof getBizPoint == "function") {
                    var pointJson = getBizPoint();
                    lon = pointJson.lon;
                    lat = pointJson.lat;
                }

                //确定中心位置
                var point = new BMap.Point(lon, lat);
                map.centerAndZoom(point, zoomSize);


                //标注
                marker = new BMap.Marker(point);// 创建标注
                map.addOverlay(marker);             // 将标注添加到地图中
                marker.enableDragging();           // 可拖拽
                marker.addEventListener("dragend", setBizValue);

                // 添加带有定位的导航控件
                var navigationControl = new BMap.NavigationControl({
                    // 靠左上角位置
                    anchor: BMAP_ANCHOR_TOP_LEFT,
                    // LARGE类型
                    type: BMAP_NAVIGATION_CONTROL_LARGE,
                    // 启用显示定位
                    enableGeolocation: true
                });
                map.addControl(navigationControl);

                var geoc = new BMap.Geocoder();


                //输入地址事件处理 start
                var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
                    {
                        "input": "suggestId2"
                        , "location": map
                    });

                ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
                    var str = "";
                    var _value = e.fromitem.value;
                    var value = "";
                    if (e.fromitem.index > -1) {
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

                    value = "";
                    if (e.toitem.index > -1) {
                        _value = e.toitem.value;
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
                    G("searchResultPanel2").innerHTML = str;
                });

                var myValue;
                ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
                    var _value = e.item.value;
                    myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                    G("searchResultPanel2").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

                    let v3 = document.getElementById("txt");
                    v3.value = myValue;
                    v3.dispatchEvent(new Event('input'))

                    setPlace();
                });

                function setPlace() {
                    map.clearOverlays();    //清除地图上所有覆盖物
                    function myFun() {
                        var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                        setBizValueForPoint(pp);
                        map.centerAndZoom(pp, zoomSize);
                        marker = new BMap.Marker(pp);
                        marker.enableDragging();           // 可拖拽
                        map.addOverlay(marker);    //添加标注
                        marker.addEventListener("dragend", setBizValue);
                    }

                    var local = new BMap.LocalSearch(map, { //智能搜索
                        onSearchComplete: myFun
                    });
                    local.search(myValue);
                }

                function G(id) {
                    return document.getElementById(id);
                }

                //输入地址事件处理 end

                //地址转坐标
                function addrSearch(serachAddr) {
                    // 创建地址解析器实例
                    var myGeo = new BMap.Geocoder();
                    // 将地址解析结果显示在地图上,并调整地图视野
                    if (!serachAddr) {
                        serachAddr = $("#suggestId2").val();
                    }
                    myGeo.getPoint(serachAddr, function (point) {
                        if (point) {
                            setBizValueForPoint(point);
                            map.clearOverlays();
                            map.centerAndZoom(point, zoomSize);
                            marker = new BMap.Marker(point);
                            marker.enableDragging();           // 可拖拽
                            map.addOverlay(marker);    //添加标注
                            marker.addEventListener("dragend", setBizValue);
                        } else {
                            console.log("search click no results!")
                        }
                    });
                }

                //业务方法 start
                //根据事件,设置经纬度和地址
                function setBizValue(e) {
                    var point = e.point;
                    setBizValueForPoint(point);
                }

                //根据Point,设置经纬度和地址
                function setBizValueForPoint(point) {
                    lon = point.lng;
                    lat = point.lat;

                    geoc.getLocation(point, function (rs) {
                        var addComp = rs.addressComponents;
                        addr = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                        if (typeof setBizFun == "function") {
                            setBizFun({lon: lon, lat: lat, addr: addr});
                        }
                    });

                    let v1 = document.getElementById("lng");
                    v1.value = lon;
                    v1.dispatchEvent(new Event('input'))

                    let v2 = document.getElementById("lat");
                    v2.value = lat;
                    v2.dispatchEvent(new Event('input'))

                }

                //根据marker,设置经纬度和地址
                function setBizValueForMarker() {
                    var point = marker.getPosition();
                    setBizValueForPoint(point);
                }
            },
            //分页查询
            findPage() {
                if (this.pagination.queryString != null && this.pagination.queryString !== "") {
                    let param = {
                        currentPage: 1,//页码
                        pageSize: this.pagination.pageSize,
                        queryString: this.pagination.queryString
                    };
                    axios.post("/map/findPage.do", param).then((response) => {
                        this.dataList = response.data.rows;
                        this.pagination.total = response.data.total;
                    });
                } else {
                    let param = {
                        currentPage: this.pagination.currentPage,//页码
                        pageSize: this.pagination.pageSize,
                        queryString: this.pagination.queryString
                    };
                    axios.post("/map/findPage.do", param).then((response) => {
                        this.dataList = response.data.rows;
                        this.pagination.total = response.data.total;
                    });
                }
            },

            // 重置表单
            resetForm() {
                this.formData = {};
                this.imageUrl = null;
            },
            // 弹出添加窗口
            handleCreate() {
                //弹出新增窗口
                this.dialogFormVisible = true;
                //调用重置表单
                this.resetForm();

            },
            // 弹出编辑窗口
            handleUpdate(row) {
                this.resetForm();
                this.dialogFormVisible4Edit = true;
                axios.get("/map/findById.do?id=" + row.id).then((resp) => {
                    if (resp.data.flag) {
                        this.formData = resp.data.data;
                        this.imageUrl = resp.data.data.img
                    } else {
                        this.$message.error(resp.data.message)
                    }
                })
            },
            findditu1() {
                let element = document.getElementById("l-map");
                let element1 = document.getElementById("suggestId");
                if (element.style.display=="none"){
                element.style.display = "";
                    element1.style.display="";
                    this.createMap1();
                }else {
                    element.style.display="none";
                    element1.style.display="none";
                }
            },
            findditu2() {
                let element = document.getElementById("map2");
                let element1 = document.getElementById("suggestId2");
                if (element.style.display=="none"){
                    element.style.display = "";
                    element1.style.display="";
                    this.createMap1();
                }else {
                    element.style.display="none";
                    element1.style.display="none";
                }
            },

            //切换页码
            handleCurrentChange(currentPage) {
                this.pagination.currentPage = currentPage;
                this.findPage();
            },
            // 删除
            handleDelete(row) {
                this.$confirm("你确定要删除当前数据吗?", "提示", {
                    type: 'warning'
                }).then(() => {
                    axios.get("/map/delete.do?id=" + row.id).then((resp) => {
                        if (resp.data.flag) {
                            this.$message({
                                type: 'succss',
                                message: resp.data.message
                            });

                        } else {
                            this.$message.error(resp.data.message);
                        }
                    }).finally((resp => {
                        this.findPage();
                    }));
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: "操作取消"
                    })
                })
            },
            handleAdd() {
                this.$refs['dataAddForm'].validate((valid) => {
                    this.$forceUpdate()
                    //表单校验
                    if (valid) {
                        //表单校验通过,发送ajax请求,讲录入的数据提交到后台进行处理
                        axios.post("/map/add.do", this.formData).then((response) => {
                            //先把提交框关闭,然后发送请求和表单参数,
                            this.dialogFormVisible = false;
                            // 接收判断后端传过来的flag是否为true,执行成功,
                            if (response.data.flag) {
                                //新增成功后,重新调用分页查询方法,查询出最新的数据
                                this.findPage();
                                //成功的提示信息
                                this.$message({
                                    message: response.data.message,
                                    type: 'success',
                                });
                            } else {
                                //不通过
                                this.$message.error(response.data.message);
                            }
                        }).finally(() => {
                            this.findPage();
                        });
                    } else {
                        this.$message.error("表单数据校验失败,请检查输入信息是否正确");
                        return false;
                    }
                })
            },
            handleClick(tab, event) {

            },
            handleAvatarSuccesss(response, file) {
                //我模型数据ImgaeUrl赋值,用于预览
                /*  this.imageUrl='http://qfjm1t11q.hd-bkt.clouddn.com/'+response.data;*/
                this.imageUrl = response.data;
                this.$message({
                    type: response.flag ? 'success' : 'error',
                    message: response.message
                });
                this.formData.img = response.data;
            },
            //上传图片之前执行
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$message.error('上传套餐图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传套餐图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },


        }
    });
</script>
</html>

实体类

package com.ybb.pojo;

import java.io.Serializable;

/**
 * Description :
 * Version :1.0
 */
public class Address implements Serializable {
    private Integer id;
    private String name;//名称
    private Integer telephone;//电话
    private String longitude;//经度
    private String latitude;//纬度
    private String img;//图片
    private String address;//地址

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getTelephone() {
        return telephone;
    }

    public void setTelephone(Integer telephone) {
        this.telephone = telephone;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

controller

package com.ybb.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ybb.constant.MessageConstant;
import com.ybb.entity.PageResult;
import com.ybb.entity.QueryPageBean;
import com.ybb.entity.Result;
import com.ybb.pojo.Address;
import com.ybb.pojo.CheckItem;
import com.ybb.service.AddressService;
import com.ybb.utils.ALiYunUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * Description :
 * Version :1.0
 */
@RestController
@RequestMapping("/map")
public class AddressController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private AddressService addressService;

    //文件上传
    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile) throws IOException {
        //TODO 记得做数据校验,校验数据的大小,类型,还有文件名拼接时注意长度


//处理后缀,uuid+.jpg拼接
        String originalFilename = imgFile.getOriginalFilename();//原始文件名
        int index = originalFilename.lastIndexOf(".");
        String extention = originalFilename.substring(index); //.jpg

        String fileName = UUID.randomUUID().toString() + extention;
        try {
            String url = ALiYunUtils.add(imgFile.getBytes(), fileName);
            System.out.println();
            jedisPool.getResource().sadd("health-img", fileName);

            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, url);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }


    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = addressService.pageQuery(
                queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString());
        return pageResult;
    }


    @RequestMapping("/add")
    public Result add(@RequestBody Address address) {
        //因为前段传来的是json格式的数据,需要加入requestbody来封装
        try {
            addressService.add(address);
            jedisPool.getResource().srem("health-img", address.getImg());
        } catch (Exception e) {
            //服务调用失败
            return new Result(false, "地图新增失败");
        }
        return new Result(true, "地图新增成功");
    }


    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            addressService.deleteById(id);
        } catch (Exception e) {
            return new Result(false, "地图删除失败");
        }
        return new Result(true, "地图删除成功");
    }


    @RequestMapping("/edit")
    public Result edit(@RequestBody Address address) {
        try {
            addressService.edit(address);
        } catch (Exception e) {
            return new Result(false, "地图编辑失败");
        }
        return new Result(true, "地图编辑成功");
    }


    @RequestMapping("/findById")
    public Result findById(Integer id) {
        Address address = null;
        try {
            address = addressService.findById(id);
        } catch (Exception e) {
            return new Result(false, "查询失败");
        }
        return new Result(true, "查询成功", address);
    }


    @RequestMapping("/findAllmap")
    public List<String>findAllmap(){
      return addressService.findAllmap();
    }


}

service

package com.ybb.service;

import com.ybb.entity.PageResult;
import com.ybb.pojo.Address;

import java.util.List;

/**
 * Description :
 * Version :1.0
 */
public interface AddressService {

    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString);


    void deleteById(Integer id);


    void edit(Address address);

    void add(Address address);


    Address findById(Integer id);


    List<String>findAllmap();
}

serviceImpl

package com.ybb.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ybb.dao.AddressDao;
import com.ybb.entity.PageResult;
import com.ybb.pojo.Address;
import com.ybb.pojo.CheckItem;
import com.ybb.service.AddressService;
import com.ybb.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Description :
 * Version :1.0
 */
@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {

   @Autowired
   private AddressDao addressDao;

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {

        Page<Address> addresses;
        PageHelper.startPage(currentPage, pageSize);
        addresses=   addressDao.selectByCondition(queryString);


        long total = addresses.getTotal();
        List<Address> rows = addresses.getResult();

        return new PageResult(total, rows);
    }

    @Override
    public void deleteById(Integer id) {
        if (id < 0 || id == null) {
            return;
        }
        //删中间表再删主表
        addressDao.deleteCenter(id);
        addressDao.deleteById(id);
    }


    @Override
    public void edit(Address address) {

        addressDao.edit(address);
    }


    @Override
    public void add(Address address) {
        //要进行数据合法性校验
        addressDao.add(address);
    }


    @Override
    public Address findById(Integer id){
      return   addressDao.findById(id);
    }

    @Override
    public List<String> findAllmap() {
     return   addressDao.findAllmap();
    }

}

dao

package com.ybb.dao;

import com.github.pagehelper.Page;
import com.ybb.pojo.Address;
import com.ybb.pojo.CheckItem;

import java.util.List;

/**
 * Description :
 * Version :1.0
 */
public interface AddressDao {
    public Page<Address>selectByCondition(String queryString);


   void deleteById(Integer id);

   void deleteCenter(Integer id);


    void edit(Address address);

    void add(Address address);

    List<String> findAllmap();

    Address findById(Integer id);
}

dao.xml

<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.ybb.dao.AddressDao">
    <delete id="deleteById">
        delete from t_address where id =#{id}
    </delete>

    <delete id="deleteCenter" parameterType="int">
        delete from t_order_address where address_id=#{id}
    </delete>


    <select id="selectByCondition" parameterType="string" resultType="com.ybb.pojo.Address">
        select  * from t_address
        <if test="value !=null and value.length > 0">
            where address like  concat ("%",concat(#{value}),"%") or name like concat("%",concat(#{value}),"%")
        </if>
    </select>

    <insert id="add" parameterType="com.ybb.pojo.Address">
    insert into t_address(name,telephone,longitude,img,address,latitude)
    values
    (#{name},#{telephone},#{longitude},#{img},#{address},#{latitude})
</insert>



    <update id="edit" parameterType="com.ybb.pojo.Address">
        update t_address
        <set>
            <if test="name != null">
                name = #{name},
            </if>
            <if test="telephone != null">
                telephone = #{telephone},
            </if>
            <if test="longitude != null">
                longitude = #{longitude},
            </if>
            <if test="img != null">
                img = #{img},
            </if>
            <if test="address != null">
                address = #{address},
            </if>
            <if test="latitude != null">
                latitude = #{latitude},
            </if>
        </set>
        where id = #{id}
    </update>


    <select id="findById" parameterType="int" resultType="com.ybb.pojo.Address">
        select * from t_address where id = #{id}
   </select>

    <select id="findAllmap" resultType="java.lang.String">
        select address from t_address
    </select>
</mapper>

知识库导入

增删改查,模板下载和上传文件,需要自己建库建表,我这里删了些字段,建库的时候一定要加上id,字段长度一定要有,不然插入数据的时候会不够

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
sport.html

<!DOCTYPE html>
<html>
<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>传智健康</title>
    <meta name="description" content="传智健康">
    <meta name="keywords" content="传智健康">
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../plugins/elementui/index.css">
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../css/style.css">
</head>
<body class="hold-transition">
<div id="app">
    <div class="content-header">
        <h1>知识库管理<small>运动库管理</small></h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>运动库管理</el-breadcrumb-item>
            <el-breadcrumb-item>知识库管理</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="boxMain">
            <el-button style="margin-bottom: 20px;margin-right: 20px" type="primary" @click="downloadTemplate()">模板下载</el-button>
            <el-upload action="/sport/upload.do"
                       name="excelFile"
                       :show-file-list="false"
                       :on-success="handleSuccess"
                       :before-upload="beforeUpload">
                <el-button type="primary">上传文件</el-button>
            </el-upload>
        </div>

    </div>
    <div class="app-container">
        <div class="box">
            <div class="filter-container">
                <el-input placeholder="编号/运动名" v-model="pagination.queryString" style="width: 200px;" class="filter-item"></el-input>
                <el-button @click="findPage()" class="dalfBut">查询</el-button>
                <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button><br>


            </div>
            <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
                <el-table-column  align="center" type="selection">
                    <template>
                        <div>
                            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                        </div>
                        <div style="margin: 15px 0;"></div>
                    </template>
                </el-table-column>
                <el-table-column type="index" align="center" label="序号"></el-table-column>
                <el-table-column prop="number" label="编号" align="center"></el-table-column>
                <el-table-column prop="sportName" label="运动名称" align="center"></el-table-column>

                <el-table-column prop="sportTime" label="运动时间" align="center"></el-table-column>
                <el-table-column prop="burnCalories" label="消耗卡路里" align="center"></el-table-column>

                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination
                        class="pagiantion"
                        @current-change="handleCurrentChange"
                        :current-page="pagination.currentPage"
                        :page-size="pagination.pageSize"
                        layout="total, prev, pager, next, jumper"
                        :total="pagination.total">
                </el-pagination>
            </div>
            <!-- 新增标签弹层 -->
            <div class="add-form">
                <el-dialog title="新增会员" :visible.sync="dialogFormVisible">
                    <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
                    <template>
                        <el-tabs v-model="activeName" type="card">
                            <el-tab-pane label="基本信息" name="first">
                                <el-form label-position="right" label-width="100px">

                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="编号" prop="number">
                                                <el-input v-model="formData.number"/>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="运动名称" prop="sportName">
                                                <el-input v-model="formData.sportName"/>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                    <el-row>
                                        <el-col :span="6">
                                            <el-form-item label="运动时间" prop="sportTime">
                                                <el-input v-model="formData.sportTime"/>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="消耗卡路里" prop="BurnCalories">
                                                <el-input v-model="formData.BurnCalories" ></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                </el-form>
                            </el-tab-pane>

                        </el-tabs>
                    </template>
                    </el-form>
                    <!--</el-form>-->
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="handleAdd()">确定</el-button>
                    </div>

                </el-dialog>
            </div>

            <!-- 编辑标签弹层 -->
            <div class="add-form">
                <el-dialog title="新增会员" :visible.sync="dialogFormVisible4Edit">
                    <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" label-width="100px">

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="编号" prop="number">
                                    <el-input v-model="formData.number"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="运动名称" prop="sportName">
                                    <el-input v-model="formData.sportName"/>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="运动时间" prop="sportTime">
                                    <el-input v-model="formData.sportTime"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="消耗卡路里" prop="BurnCalories">
                                    <el-input v-model="formData.BurnCalories" ></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                    </el-form>
                    </el-tab-pane>

                        </el-tabs>

                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible4Edit = false">取消</el-button>

                        <el-button type="primary" @click="handleEdit()">确定</el-button>
                    </div>
                </el-dialog>
            </div>
        </div>
    </div>
</div>
</body>
<!-- 引入组件库 -->
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>
    var vue = new Vue({
        el: '#app',
        data:{
            pagination: {//分页相关模型数据
                currentPage: 1,//当前页码
                pageSize:10,//每页显示的记录数
                total:0,//总记录数
                queryString:null//查询条件
            },
            dataList: [],//当前页要展示的分页列表数据
            formData: {},//表单数据
            dialogFormVisible: false,//增加表单是否可见
            dialogFormVisible4Edit:false,//编辑表单是否可见
            activeName:"first",
            rules: {//校验规则
                code: [{ required: true, message: '项目编码为必填项', trigger: 'blur' }],
                name: [{ required: true, message: '项目名称为必填项', trigger: 'blur' }]
            }
        },
        //钩子函数,VUE对象初始化完成后自动执行
        created() {
            this.findPage();
        },
        methods: {
            //下载模板文件
            downloadTemplate(){
                window.location.href="/template/sport.xls";
            },
            //上传成功提示
            handleSuccess(response, file) {
                if(response.flag){
                    this.$message({
                        message: response.message,
                        type: 'success'
                    });
                }else{
                    this.$message.error(response.message);
                }
                console.log(response, file, fileList);
                this.findPage();
            },
            //上传之前进行文件格式校验
            beforeUpload(file){
                const isXLS = file.type === 'application/vnd.ms-excel';
                if(isXLS){
                    return true;
                }
                const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                if (isXLSX) {
                    return true;
                }
                this.$message.error('上传文件只能是xls或者xlsx格式!');
                return false;
            },


            // 删除
            handleDelete(row) {
                this.$confirm("你确定要删除当前数据吗?","提示",{
                    type:'warning'
                }).then(()=>{
                    axios.get("/sport/delete.do?id=" + row.id).then((resp)=>{
                        if (resp.data.flag){
                            this.$message({
                                type:'succss',
                                message:resp.data.message
                            });

                        }else {
                            this.$message.error(resp.data.message);
                        }
                    }).finally((resp=>{
                        this.findPage();
                    }));
                }).catch(()=>{
                    this.$message({
                        type:'info',
                        message:"操作取消"
                    })
                })
            },
            //添加
            handleAdd () {
                //表单校验通过,发送ajax请求,讲录入的数据提交到后台进行处理
                axios.post("/sport/add.do",this.formData).then((response)=>{
                    //先把提交框关闭,然后发送请求和表单参数,
                    this.dialogFormVisible=false;
                    // 接收判断后端传过来的flag是否为true,执行成功,
                    if (response.data.flag){
                        //新增成功后,重新调用分页查询方法,查询出最新的数据
                        this.findPage();
                        //成功的提示信息
                        /*      this.$message.success(response.data.message);
                        */      this.$message({
                            message:response.data.message,
                            type:'success',
                        });
                    }else {
                        //不通过
                        this.$message.error(response.data.message);
                    }
                }).finally(()=>{
                    this.findPage();
                });
            },
            //新建
            handleCreate () {

                //弹出新增窗口
                this.dialogFormVisible=true;
                //调用重置表单
                this.resetForm();

            },

            //分页查询
            findPage() {
                if (this.pagination.queryString!=null&&this.pagination.queryString!==""){
                    let param={
                        currentPage: 1,//页码
                        pageSize: this.pagination.pageSize,
                        queryString: this.pagination.queryString
                    };
                    axios.post("/sport/findPage.do",param).then((response)=>{
                        this.dataList=response.data.rows;
                        this.pagination.total=response.data.total;
                    });
                }else {
                    let param = {
                        currentPage: this.pagination.currentPage,//页码
                        pageSize: this.pagination.pageSize,
                        queryString: this.pagination.queryString
                    };
                    axios.post("/sport/findPage.do",param).then((response)=>{
                        this.dataList=response.data.rows;
                        this.pagination.total=response.data.total;
                    });
                }
            },
            // 重置表单
            resetForm() {
                this.formData={};//重置数据
            },
            //切换页码
            handleCurrentChange(currentPage) {
                this.pagination.currentPage=currentPage;
                this.findPage();
            },

            //编辑
            handleEdit() {
                this.$refs['dataEditForm'].validate((valid)=>{
                    if (valid){
                        axios.post("/sport/edit.do",this.formData).then(res=>{
                            if (res.data.flag){
                                this.$message({
                                    type:'success',
                                    message:res.data.message
                                });
                            }
                        }).finally(()=>{
                            this.findPage();
                            this.dialogFormVisible4Edit=false;
                        })
                    }else {
                        this.$message.error("表单数据效验失败")
                        return false;
                    }
                })
            },
            //编辑
            handleUpdate(row) {
                this.dialogFormVisible4Edit=true;

                axios.post("/sport/findById.do?id="+row.id).then(res=>{
                    if (res.data.flag){
                        this.formData=res.data.data;
                    }else {
                        this.$message.error(res.data.message);
                    }
                })
            }
        }
    })
</script>
</html>

java

package com.ybb.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ybb.constant.MessageConstant;
import com.ybb.entity.PageResult;
import com.ybb.entity.QueryPageBean;
import com.ybb.entity.Result;
import com.ybb.pojo.Etiology;
import com.ybb.pojo.Sport;
import com.ybb.service.EtiologyService;
import com.ybb.service.SportService;
import com.ybb.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Description :
 * Version :1.0
 */
@RestController
@RequestMapping("/sport")
public class SportController {

    @Reference
    private SportService sportService;

    @RequestMapping("/add")
    public Result add(@RequestBody Sport sport){
        //因为前段传来的是json格式的数据,需要加入requestbody来封装
        try {
            sportService.add(sport);
        }catch (Exception e){
            //服务调用失败
            return new Result(false,MessageConstant.ADD_CHECKGROUP_FAIL);
        }
        return new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);
    }


    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult= sportService.pageQuery(
                queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString());
        return pageResult;
    }

    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            sportService.deleteById(id);
        }catch (Exception e){
            return new Result(false,MessageConstant.DELETE_CHECKGROUP_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_CHECKGROUP_SUCCESS);
    }


    @RequestMapping("/edit")
    public Result edit(@RequestBody  Sport sport){
        try {
            sportService.edit(sport);
        }catch (Exception e){
            return new Result(false, MessageConstant.EDIT_CHECKITEM_FAIL);
        }
        return new Result(true, MessageConstant.EDIT_CHECKITEM_SUCCESS);
    }


    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Sport byId = sportService.findById(id);
            return new Result(true,MessageConstant.QUERY_CHECKITEM_SUCCESS,byId);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL);
        }
    }




    @RequestMapping("/upload")
    public Result upload(MultipartFile excelFile){
        try {
            List<String[]> list = POIUtils.readExcel(excelFile);
            List<Sport>data=new ArrayList<>();
            for (String[] strings : list) {
                Sport sport = new Sport();
                sport.setId(Integer.parseInt(strings[0]));
                sport.setNumber(String.valueOf(strings[1]));
                sport.setSportName(String.valueOf(strings[2]));
                sport.setSportTime(String.valueOf(strings[3]));
                sport.setBurnCalories(String.valueOf(strings[4]));
                data.add(sport);
            }
            //通过dubbo远程调用
            sportService.add2(data);

            return new Result(true,MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }
}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值