Django 桌面保存 Excel

2024-09-30 18:23:28 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我想我的问题很简单,但是我。。。有些问题:)

因此,在我用Django编写的应用程序中,我调用了使用Ajax创建Excel文件,如下所示:

            $.ajax({
                url: '/ajax-send-xls-desktop/',
                type: 'POST',
                contentType: "application/vnd.ms-excel",
                data: JSON.stringify(data_xls),
                dataType: 'text',
                success: function(result) {
                    window.open('data:application/vnd.ms-excel,' + result);
                }
            });

在后台,我创建Excel文件并返回如下响应:

^{pr2}$

我收到的都是很多字符:

    N*8X"��1���Arial1���Arial1���Arial1���Arial1���Arial1���Arial1���Arial1���Arial
�General���� �� ���� �� ���� �� ���� �� ���� �� ���� �� ���� �� ���� �� ���� �� ���� ��
���� �� ���� �� ���� �� ���� �� ���� �� ���� �� �� �� �� �� �� �� ���`��Opis pozycji��
PDane wygnerowane przez Interzam - Internetowa Platforma Zarzdzania Zam�wieniamiSIDCPV

有人能确认问题出在字符集编码上吗?在


Tags: 文件django应用程序urldataapplicationajaxresult
3条回答

Data URI scheme提到base64编码作为一个选项。另一种方法是进行相关的字符编码。我建议你以64为基数对数据进行编码。Here is a question这将帮助你做到这一点。在

这对我有用:

response = HttpResponse(mimetype="application/ms-excel")
response['Content-Disposition'] = "attachment; filename=%s" % "excel.xls"
book.save(response)
return response

我只是链接到查看网址和在结果对话框显示。有了ajax call它就无法完成。。。在

更新:

我找到了一个解决方案(使用了表单的iframe)来解决您需要在这里动态请求文件-Download a file by jQuery.Ajax。您可以使用@JohnCulviner-http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/或我的小函数ajax_download创建的插件:

^{pr2}$

在您的案例中(例如使用click事件):

$('#someid').on('click', function() {
    ajax_download('/ajax-send-xls-desktop/', data_xls, 'data');
});

你真的需要使用Ajax吗?它似乎过于复杂了。在

我的应用程序中有excel下载,但它们是标准的Django视图。其中大多数是基于类的泛型视图,我在其中重写了render_to_response方法,并用excel设置了内容类型。在

因此,我有一个对象的标准ListView来生成HTML,并且ExcelListView重写了render to response方法,来编写excel而不是将其传递给HTML模板。在

class ViewToExcel():
    """
    This class will implement the excel writing functionality, by overwriting the render_to_response method
    """
    headings2attrributes = {}  # empty default

    def render_to_response(self, context, **response_kwargs):
        """
        Returns a response with a an excel sheet.
        """
        self.generate_headings()   # specific to my application

        wbk = xlwt.Workbook()
        sheet = wbk.add_sheet('sheet 1')

        # Create the HttpResponse object with the appropriate CSV header.
        response = HttpResponse(mimetype='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=Report.xls'

       row_num = 0
       col_num = 0 

       ## write row of headings
       for hd_att in self.headings2attrributes :
            sheet.write(row_num, col_num , hd_att[0])
            col_num += 1
            row_num += 1

      object_list = self.get_queryset()

    # write rows of data ## again, this is fairly specific to my implementation
    for object  in object_list:   ## go through each object instance in queryset
        self.write_object_row(sheet, row_num, 0 , object)
        row_num += 1
    wbk.save(response)    
    return response



class MyView(ListView):
    """
    This will produce the standard HTML page (which should contain a link to the excel download)
    """
    context_object_name = "my_list"
    template_name = "sequencing/MyView.html"

    def get_queryset(self):
       """
       get your objects and populate a queryset / querydict here
       """
        ...        
        ...
        return MyObjects.all().filter(blah, blah= blah)


class MyExcelView( ViewToExcel , MyView):
    """
    This view will subclass both the ViewToExcel class as well as MyView. 
    When it is called it will reuse the get_queryset method from MyView, but will use RenderToResponse from ViewToExcel - producing excel response, rather than HTML
    The way I have implemented it is that the MyExcelView provides HeadingsToAttributes dictionary, which is used to write the excel. 
    """       
    headings2attrributes_template = [
        ['heading', 'attribbute' ]  , 
        ['heading_2', 'callable' ], 

相关问题 更多 >