python的将数据生成excel功能
高洛峰
高洛峰 2017-04-17 18:00:09
0
2
504

求教,excel生成好了,用的xlrd 如何将excel保存到本地来?

直接w.save('xxxx.xls')这保存在服务器的硬盘上了

客户使用的时候如何把它保存在客户的电脑上?

多谢

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
小葫芦

Output the file stream. When the user clicks to download, the output Content-Type is application/ms-excel. You can refer to the link description of this article

小葫芦

This is how I implemented it. The front-end page adds a click event to the export button. After clicking, use ajax to send data to the corresponding URL. Use xlrd to generate and save xlxs to the path specified by the server. Finally, return the file name (filename). Click the download button on the front-end. You can download it locally.

Front page:

<style type="text/css">
    @import "/static/order/jquery-ui.min.css";
</style>

<script type="text/javascript" src="/static/order/jquery-ui.min.js"></script>

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

        $('#export').click(function(){
            $('button').attr('disabled', 'disabled')
            $('button').text('正在处理,请耐心等待...')
            $('#download').hide()

            $.ajax({
                type: "POST",
                data: $('#order_filter_form').serialize(),
                url: "{{ url_for('.orders_export_search') }}",
                success: function(filename){
                    $('button').removeAttr('disabled')
                    $('button:first').text('筛选')
                    $('button:last').text('导出')

                    $('#download').show();
                    $('#download a').attr('href', "/static/order/export/"+filename)
                }
            })
            return false;
        })
    })
</script>

<p id="admin_order_control" class="well">
    <form class="form-inline" id="order_filter_form">
        <p class="col-md-2">
            <p class="form-group">
                <label for="status">订单状态</label>
                <select name="status" class="form-control">
                    <option value="">--请选择--</option>
                    <option value="0">关闭</option>
                    <option value="1">初始订单</option>
                    <option value="2">待支付</option>
                    <option value="3">订单处理中</option>
                </select>
            </p>

            <p class="form-group">
                <button type="submit" class="btn btn-primary">筛选</button>
                <button type="submit" class="btn btn-default" id="export">导出</button>
            </p>
            <p id="download" style="display:none;">
                <a href="#" class="btn btn-danger">点击下载导出文件</a>
            </p>
        </p>

        <p class="clearfix"></p>
    </form>
</p>

Server:

@admin_order_bp.route('/orders/export_search', methods=['POST'])
@json_view
def orders_export_search():
    user = request.environ['user']

    dict_item = {}
    for key in request.form:
        dict_item[key] = request.form[key]
    dict_item.update({'user_shop_ids':  user.shops})

    orders = Order.search(dict_item, {'page': 1, 'per_page': 99999})[0]
    filename = OrderExporter.rows_to_xls(orders)
    return filename

model layer:

# 根据数据生成excel文件
    @classmethod
    def rows_to_xls(cls, order_rows):
        filename = '%s_%s.xls' % (datetime.datetime.now().strftime("%Y%m%d"), cls.generate_random_str())
        filepath = '%s/%s' % (_updir, filename) # _updir就是文件的存放路径
        book = xlwt.Workbook(encoding="utf-8")
        sheet1 = book.add_sheet("Sheet 1")

        for i, val in enumerate(cls.csv_headline()):
            # (行,列,值)
            sheet1.write(0, i, val)

        for i, order_row in enumerate(order_rows):
            utf8_line = cls.order_line(order_row)
            for j, val in enumerate(utf8_line):
                sheet1.write(i+1, j, val)

        book.save(filepath)
        return filename
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!