создание файла Excel по клику в колбе с помощью jquery - PullRequest
0 голосов
/ 08 мая 2019

привет. В настоящее время я работаю над отчетом о конкретном сотруднике в течение определенного промежутка времени. имя сотрудника и диапазон дат выбираются на html-странице, и эти три данные отправляются в колбу с помощью jquery, и у меня есть 0% знание jquery но кое-как, как мне удалось отправить данные в колбу мой файл Excel создается как я хочу, но файл не загружается, я не знаю, почему я думаю, что мой метод send_file выглядит хорошо Мне нужна помощь, так как я не знаю о JQuery или JS, так что я думаю, что именно здесь я делаю что-то не так я ставлю свою колбу и HTML-код вниз, любая помощь будет здорово

Колба: -

@app.route('/excel_sheet_maker')
def mk_excel_sheet():

    sort_user = request.args.get('sort_user2', 'abc1')
    from_date = request.args.get('from_date2', 'abc2')
    to_date = request.args.get('to_date2', 'abc3')
    company_name = session.get('company_name', 'abc4')

    print(f"{sort_user}\n{from_date}\n{to_date}\n{company_name}")

    file_name = f"{sort_user}-{from_date[:2]}-{from_date[3:5]}-{from_date[6:10]}-{to_date[:2]}-{to_date[3:5]}-{to_date[6:10]}.xlsx"
    print("file_name = ",file_name)
    file_path = 'static/excel/'+str(file_name)
    print("file_path = ", file_path)
    #print(from_date, to_date)
    try:

        #cur = connn.cursor()
        cur = mysql.connection.cursor()

        query = "SELECT date_format, type, username, time_in, address_in, time_out, address_out FROM (SELECT date_today AS 'date_format', 'attendence' AS 'type', user AS 'username', company_name AS 'cn', STR_TO_DATE(in_time, '%d-%m-%Y %H:%i:%s') AS 'time_in', in_address AS 'address_in', STR_TO_DATE(out_time, '%d-%m-%Y %H:%i:%s') AS 'time_out', out_address AS 'address_out' FROM attendence UNION ALL SELECT add_time, 'visit', username, company_name, STR_TO_DATE(visit_time_in, '%d-%m-%Y %H:%i:%s'), location_in, STR_TO_DATE(visit_time_out, '%d-%m-%Y %H:%i:%s'), location_out FROM visits) t WHERE t.username = '"+str(sort_user)+"' AND t.cn = '"+str(company_name)+"' AND time_in BETWEEN STR_TO_DATE('"+str(from_date)+"', '%d-%m-%Y %H:%i:%s') AND STR_TO_DATE('"+str(to_date)+"', '%d-%m-%Y %H:%i:%s') ORDER BY time_in ASC;"

        cur.execute(query)
        data = cur.fetchall()
        print("dictionary data = ", data)
        result = []
        for item in data:
            result.append(list(item.values()))

        book = xlsxwriter.Workbook(file_path)
        sheet = book.add_worksheet('sheet1')
        bold = book.add_format({'bold': True})
        text_wrap = book.add_format({'text_wrap': True})

        sheet.write(0,0,'DATE',bold)
        sheet.write(0,1,'TYPE',bold)
        sheet.write(0,2,'USERNAME',bold)
        sheet.write(0,3,'TIME IN',bold)
        sheet.write(0,4,'LOCATION IN',bold)
        sheet.write(0,5,'TIME OUT',bold)
        sheet.write(0,6,'LOCATION OUT',bold)

        r = 2
        for r, row in enumerate(result):
            print(f"r = {r} | row = {row}")
            r+=1
            # row = row.values()
            # print("dict values = ", row)
            # row = list(row)
            # print("list row = ", row)
            # date = row[0]
            # row_date = row[0]
            #print(f"{date}|{row_date}")
            #if row_date is date

            for c, col in enumerate(row):
                print(f"c = {c} | col = {col}")
                sheet.set_column('{0}:{0}'.format(chr(c + ord('A'))), len(str(col)) + 2)
                sheet.write(r, c, col if type(col) is not datetime else col.strftime('%d-%m-%Y %H:%M:%S'), text_wrap)

        book.close()

    except Exception as e:
        print("ERROR = ", e)

    try:
        # return Response(data, mimetype='text/csv', headers= {"Content-disposition":
  #                "attachment; filename=myplot.csv"})
        return send_file(file_path, mimetype='text/xlsx', attachment_filename=file_name, as_attachment=True)
    except Exception as e:
        print("FILE ERROR = ", e)

HTML: -

{% extends 'layout.html' %}

{% block body %}

<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <title>Google Maps Multiple Markers</title>
  <script src="http://maps.google.com/maps/api/js?sensor=false"
  type="text/javascript"></script>
</head>


<script type=text/javascript>
  $(function() {
    $('a#calculate').bind('click', function() {
      $.getJSON($SCRIPT_ROOT + '/_add_numbers', {
        sort_user2: $('select[name="sort_user2"]').val(),
      }, function(data) {
        $("#result").text(data.result3);
      });
      return false;
    });
  });
</script>

<script type=text/javascript>
  $(function() {
    $('a#excel').bind('click', function() {
      console.log("called exel")
      $.getJSON($SCRIPT_ROOT + '/excel_sheet_maker', {
        sort_user2: $('select[name="sort_user"]').val(),
        from_date2: $('input[name="from_date"]').val(),
        to_date2: $('input[name="to_date"]').val(),

      }, function(data) {
        // $("#result").text(data.result3);
        // $('input[name="amt"]').val('');
        // $('input[name="notes2"]').val('');
        // $('input[name="paid_to"]').attr("disabled",true);
        // document.getElementById("notes").readOnly = true;
      });
      return false;

    });
  });
</script>

<!-- <span id=result>?</span>
  <b>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</b> -->
  <!-- {{ res }} -->

  <script type=text/javascript>
    $SCRIPT_ROOT = {{ request.script_root|tojson|safe }}
  </script>

<!-- <div class="form-group">
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label>Select User : *</label><br>
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select name="sort_user2" class="form-control select2" style="width: 40%;" value="{{request.form.sort_user}}" required>
    {% for ttl_user in ttl_users %}
      <option name="{{ ttl_user['username'] }}" value="{{ ttl_user['username'] }}">{{ ttl_user['username'] }}</option>
    {% endfor %}
  </select>
</div>
<a href="#" id="calculate">click here</a> -->




<section class="content-header">
  <h1>
    View Attendance
    <small>Version 2.0</small>
  </h1>
  <ol class="breadcrumb">
    <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
    <li class="active">View Attendence</li>
  </ol>
</section>
<br>
<div class="row">
  <!-- Left col -->
  <div class="col-md-12">
    <!-- MAP & BOX PANE -->
    <div class="box box-success">
      <div class="box-header with-border">
        <h3 class="box-title"></h3>
        <div class="box-tools pull-right">
          <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
          </button>
          <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
        </div>
      </div>
      <!-- /.box-header -->
      <div class="box-body no-padding">
        <div class="row">
          <div class="col-md-12 col-sm-12">
            <div class="row">
              <div class="col-lg-6 col-xs-12">
                <form class="" action="" method="post">

                  <div class="form-group">
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label>Select User : *</label><br>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select name="sort_user" class="form-control select2" style="width: 40%;" id="username" value="{{ request.form.sort_user }}" required>
                      {% for ttl_user in ttl_users %}
                      <option name="{{ ttl_user['username'] }}" value="{{ ttl_user['username'] }}">{{ ttl_user['username'] }}</option>
                      {% endfor %}
                    </select>
                  </div>
                  <div class="col-xs-6">
                    <label>From Date : *</label>
                    <div class="input-group date">
                      <div class="input-group-addon">
                        <i class="fa fa-calendar"></i>
                      </div>
                      <input type="text" class="form-control" id="datepicker" value="{{ week_ago }}"" name="from_date" autocomplete="off">
                    </div>
                  </div>
                  <label>To Date : *</label>
                  <div class="input-group date">
                    <div class="input-group-addon">
                      <i class="fa fa-calendar"></i>
                    </div>
                    <input type="text" class="form-control" id="datepicker2" name="to_date" value="{{ today }}" autocomplete="off">
                  </div>

                  <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="btn btn-info" value="GO">
                </form>
              </div>
            </div>
            <div class="pad">
              <!-- Map will be created here -->
              <div id="map_canvas" style="width: 100%; height: 400px;"></div>
            </div>
          </div>
          <!-- /.col -->

          <!-- /.col -->

          <!-- /.row -->
        </div>
      </div>
    </div>
  </div>
</div>
<br><br>
<div class="box">
  <div class="box-header">
    <h3 class="box-title">VIEW ATTENDANCE</h3>
    <div class="pull-right box-tools">
      <button type="button" class="btn btn-info btn-sm" data-widget="collapse" data-toggle="tooltip" title="Collapse">
        <i class="fa fa-minus"></i>
      </button>
      <button type="button" class="btn btn-info btn-sm" data-widget="remove" data-toggle="tooltip" title="Remove">
        <i class="fa fa-times"></i>
      </button>
    </div>
  </div>
  <div class="container">
    <a id="excel" class="btn btn-info" title="Make EXCEL Report">EXCEL</a>
      <!-- <button id="excel" type="submit" class="btn btn-info" value="EXCEL" title="Make EXCEL Report">EXCEL</button> -->
    <!-- </a> -->
  </div>
  <div class="box-body">
    <div class="table-responsive">
      <table id="example5" class="table table-hover" width="100%">
        <thead>
          <tr>
            <th style="width:20%;">Username</th>
            <th>Checked In</th>
            <th>Location (In)</th>
            <th>Checked Out</th>
            <th>Location (Out)</th>
            <th>Notes (In)</th>
            <th>Notes (Out)</th>
            {% if mast %}
            <th>late Status</th>
            {% endif %}
          </tr>
        </thead>
        <tbody>
          {% for res2 in res %}
          <tr>
            <td>{{ res2['user'] }}</td>
            <td>{{ res2['in_time'] }}</td>
            <td>{{ res2['in_address'] }}</td>
            <td>{{ res2['out_time'] }}</td>
            <td>{{ res2['out_address'] }}</td>
            <td>{{ res2['out_reason'] }}</td>
            <td>{{ res2['in_reason'] }}</td>
            {% if mast %}
            <td>{{ res2['late_status'] }}</td>
            {% endif %}
          </tr>
          {% endfor %}
        </tbody>
        <tfoot>
          <tr>
            <th>Username</th>
            <th>Checked In</th>
            <th>Location (In)</th>
            <th>Checked Out</th>
            <th>Location (Out)</th>
            <th>Notes (In)</th>
            <th>Notes (Out)</th>
            {% if mast %}
            <th>late Status</th>
            {% endif %}
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</div>
<div class="box">
  <div class="box-header">
    <h3 class="box-title">VIEW VISITS</h3>
    <div class="pull-right box-tools">
      <button type="button" class="btn btn-info btn-sm" data-widget="collapse" data-toggle="tooltip" title="Collapse">
        <i class="fa fa-minus"></i>
      </button>
      <button type="button" class="btn btn-info btn-sm" data-widget="remove" data-toggle="tooltip" title="Remove">
        <i class="fa fa-times"></i>
      </button>
    </div>
  </div>
  <div class="box-body">
    <div class="table-responsive">
      <table id="example6" class="table table-hover" width="100%">
        <thead>
          <tr>
            <th style="width:20%;">Username</th>
            <th>Visit In</th>
            <th>Visit Location (In)</th>
            <th>Visit Reason (in)</th>
            <th>Visit Out</th>
            <th>Visit Location (Out)</th>
            <th>Visit Reason (Out)</th>
            <th>Place In/Out reason</th>
            <th>Customer Name</th>
            {% if mast %}
            <th>late Status</th>
            {% endif %}
          </tr>
        </thead>
        <tbody>
          {% for disp9 in disp99 %}
          <tr>
            <td>{{ disp9['username'] }}</td>
            <td>{{ disp9['visit_time_in'] }}</td>
            <td>{{ disp9['location_in'] }}</td>
            <td>{{ disp9['reason_in'] }}</td>
            <td>{{ disp9['visit_time_out'] }}</td>
            <td>{{ disp9['location_out'] }}</td>
            <td>{{ disp9['reason_out'] }}</td>
            <td>{{ disp9['destreason'] }}</td>
            <td>{{ disp9['destreasontype'] }}</td>
            <!-- <td>{{disp9['in_out']}}</td> -->
            <td>{% if disp9['in_out']=="OUT" %}<i class="fa fa-circle text-danger" title="OUT"></i>{% else %}<i class="fa fa-circle text-success" title="IN"></i>{% endif %}</td>
          </tr>
          {% endfor %}
        </tbody>
        <tfoot>
          <tr>
            <th>Username</th>
            <th>Visit In</th>
            <th>Visit Location (In)</th>
            <th>Visit Reason (in)</th>
            <th>Visit Out</th>
            <th>Visit Location (Out)</th>
            <th>Visit Reason (Out)</th>
            <th>Place In/Out reason</th>
            <th>Customer Name</th>
            {% if mast %}
            <th>late Status</th>
            {% endif %}
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</div>
<script>
  $(function () {
    $('#example1').DataTable()
    $('#example2').DataTable({
      'paging'      : true,
      'lengthChange': false,
      'searching'   : false,
      'ordering'    : true,
      'info'        : true,
      'autoWidth'   : false
    })
  })
</script>

<script>
  function today_date()
  {
    document.getElementById('e').value = new Date().toISOString().substring(0, 10);
  }
</script>

<script>
  $(document).ready(function() {
    $('#example').DataTable( {
      "pagingType": "full_numbers"
    } );
  } );
</script>

<style>
  td.highlight {
    background-color: whitesmoke !important;
  }
</style>

<script>
  $(document).ready(function() {

    $('#example5 tbody')
    .on( 'mouseenter', 'td', function () {
      var colIdx = table.cell(this).index().column;

      $( table.cells().nodes() ).removeClass( 'highlight' );
      $( table.column( colIdx ).nodes() ).addClass( 'highlight' );
    } );

    var table = $('#example5').DataTable( {
      "order" : false,
      "scrollY": "500px",
      "scrollX": true,
      "scrollCollapse": true,
      //dom: 'Bfrtip',
      // buttons: [
      // {
      //   extend: 'print',
      //   exportOptions: {
      //     columns: [ 0,1,2,3,4,5,6,7 ]
      //   }
      // },
      // {
      //   extend: 'pdfHtml5',
      //   exportOptions: {
      //     columns: [ 0,1,2,3,4,5,6,7 ]
      //   }
      // },
      // {
      //   extend: 'excelHtml5',
      //   exportOptions: {
      //     columns: [ 0,1,2,3,4,5,6,7 ]
      //   }
      // },
      // {
      //   extend: 'csvHtml5',
      //   exportOptions: {
      //     columns: [ 0,1,2,3,4,5,6,7 ]
      //   }
      // },
      // {
      //   extend: 'copyHtml5',
      //   exportOptions: {
      //     columns: [ 0,1,2,3,4,5,6,7 ]
      //   }
      // },
      // 'colvis'
      // ],
      // // initComplete: function () {

      //   this.api().columns().every( function () {

      //     var column = this;
      //     var select = $('<select class="form-control select2"><option value=""></option></select>')
      //     .appendTo( $(column.header()))
      //     .on( 'change', function () {
      //       var val = $.fn.dataTable.util.escapeRegex(
      //         $(this).val()
      //         );

      //       column
      //       .search( val ? '^'+val+'$' : '', true, false )
      //       .draw();
      //     } );

      //     column.data().unique().sort().each( function ( d, j ) {
      //       select.append( '<option value="'+d+'" selected>'+d+'</option>' )
      //     } );
      //   } );

      // }


    } );

  } );

</script>
<script>
  $(document).ready(function() {

    $('#example6 tbody')
    .on( 'mouseenter', 'td', function () {
      var colIdx = table.cell(this).index().column;

      $( table.cells().nodes() ).removeClass( 'highlight' );
      $( table.column( colIdx ).nodes() ).addClass( 'highlight' );
    } );

    var table = $('#example6').DataTable( {
      "order" : false,
      "scrollY": "500px",
      "scrollX": true,
      "scrollCollapse": true,

      // initComplete: function () {

      //   this.api().columns().every( function () {

      //     var column = this;
      //     var select = $('<select class="form-control select2"><option value=""></option></select>')
      //     .appendTo( $(column.header()))
      //     .on( 'change', function () {
      //       var val = $.fn.dataTable.util.escapeRegex(
      //         $(this).val()
      //         );

      //       column
      //       .search( val ? '^'+val+'$' : '', true, false )
      //       .draw();
      //     } );

      //     column.data().unique().sort().each( function ( d, j ) {
      //       select.append( '<option value="'+d+'" selected>'+d+'</option>' )
      //     } );
      //   } );

      // }


    } );

  } );

</script>
<script>
  $(document).ready(function() {

    $('#example7 tbody')
    .on( 'mouseenter', 'td', function () {
      var colIdx = table.cell(this).index().column;

      $( table.cells().nodes() ).removeClass( 'highlight' );
      $( table.column( colIdx ).nodes() ).addClass( 'highlight' );
    } );

    var table = $('#example7').DataTable( {
      "order" : false,
      "scrollY": "500px",
      "scrollX": true,
      "scrollCollapse": true,
      dom: 'Bfrtip',
      buttons: [
      {
        extend: 'print',
        exportOptions: {
          columns: [ 0,1,2,3,4,5,6,7 ]
        }
      },
      {
        extend: 'pdfHtml5',
        exportOptions: {
          columns: [ 0,1,2,3,4,5,6,7 ]
        }
      },
      {
        extend: 'excelHtml5',
        exportOptions: {
          columns: [ 0,1,2,3,4,5,6,7 ]
        }
      },
      {
        extend: 'csvHtml5',
        exportOptions: {
          columns: [ 0,1,2,3,4,5,6,7 ]
        }
      },
      {
        extend: 'copyHtml5',
        exportOptions: {
          columns: [ 0,1,2,3,4,5,6,7 ]
        }
      },
      'colvis'
      ],
      // initComplete: function () {

      //   this.api().columns().every( function () {

      //     var column = this;
      //     var select = $('<select class="form-control select2"><option value=""></option></select>')
      //     .appendTo( $(column.header()))
      //     .on( 'change', function () {
      //       var val = $.fn.dataTable.util.escapeRegex(
      //         $(this).val()
      //         );

      //       column
      //       .search( val ? '^'+val+'$' : '', true, false )
      //       .draw();
      //     } );

      //     column.data().unique().sort().each( function ( d, j ) {
      //       select.append( '<option value="'+d+'" selected>'+d+'</option>' )
      //     } );
      //   } );

      // }


    } );

  } );

</script>

<p id="brow"></p>

<script type="text/javascript">
  function Initialize() {

   var data2 = [
   { "Id": 1, "PlaceName": "44, Ballard Estate, Fort, Mumbai, Maharashtra, Mumbai", "GeoLong": "36.401081", "GeoLat": "10.16596", "Notes": "hello" },
   { "Id": 2, "PlaceName": "Departure Drive, Hyderabad, Ranga Reddy, Telangana, 501218, India ", "GeoLong": "36.4", "GeoLat": "10.616667" },
   { "Id": 3, "PlaceName": "Mumbai, ", "GeoLong": "35.8329809", "GeoLat": "10.63875" },
   { "Id": 4, "PlaceName": "15, Kapurbawdi, Thane West, Thane, Maharashtra, Thane", "GeoLong": "34.745159", "GeoLat": "10.7613" }
   ];
        // Google has tweaked their interface somewhat - this tells the api to use that new UI
        google.maps.visualRefresh = true;


            //Populate all location
            var locdata2 = {{ rec|tojson }}
            var Tunisie = new google.maps.LatLng(19.075984, 72.877656);


            var mapOptions = {
              zoom: 10,
              center: Tunisie,
              mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
            };
            // This makes the div with id "map_canvas" a google map
            var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
            var geocoder = new google.maps.Geocoder();

            // Using the JQuery "each" selector to iterate through the JSON list and drop marker pins
            $.each(locdata2, function (i, item) {
              geocoder.geocode({ 'address': item.in_address }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                 var latitude = results[0].geometry.location.lat();
                 var longitude = results[0].geometry.location.lng();
                       //alert(latitude);
                       pininmap = true
                       var marker = new google.maps.Marker({
                         'position': new google.maps.LatLng(latitude, longitude),
                         'map': map,
                         'animation':  google.maps.Animation.DROP,
                           // 'icon': 'http://maps.google.com/mapfiles/ms/icons/blue.png',
                           // 'title': item.in_address
                         });
                       marker.setIcon('https://maps.google.com/mapfiles/ms/icons/red-dot.png')
                       var infowindow = new google.maps.InfoWindow({
                         content: "<div class='infoDiv'><div class='col-xs-12'><h4>" + item.in_address + "</h4><p><strong>" + item.user + " - " + item.in_time + "</strong></p><p><strong>Notes</strong> - " + item.in_reason + "</p></div></div>"
                       });
                       google.maps.event.addListener(marker, 'mouseover', function () {
                         infowindow.open(map, marker);
                       });
                       google.maps.event.addListener(marker, 'click', function () {
                         infowindow.open(map, marker);
                       });
                       marker.addListener('mouseout', function() {
                        infowindow.close();
                      });



                       function toggleBounce() {
                        if (marker.getAnimation() !== null) {
                          marker.setAnimation(null);
                        } else {
                          marker.setAnimation(google.maps.Animation.BOUNCE);
                        }
                      }
                    }
                  });
            });
          }
        </script>
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDPXgPIcSXpScTu9rwDYy2LpGKRz_DcGGA"></script>

        <script type="text/javascript">
    //This code tells the browser to execute the "Initialize" method only when the complete document model has been loaded.
    $(document).ready(function () {
      Initialize();
    });



  </script>





  {% endblock %}

и краткий обзор моей jquery

<script type=text/javascript>
  $(function() {
    $('a#excel').bind('click', function() {
      console.log("called exel")
      $.getJSON($SCRIPT_ROOT + '/excel_sheet_maker', {
        sort_user2: $('select[name="sort_user"]').val(),
        from_date2: $('input[name="from_date"]').val(),
        to_date2: $('input[name="to_date"]').val(),

      }, function(data) {
        // $("#result").text(data.result3);
        // $('input[name="amt"]').val('');
        // $('input[name="notes2"]').val('');
        // $('input[name="paid_to"]').attr("disabled",true);
        // document.getElementById("notes").readOnly = true;
      });
      return false;

    });
  });
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...