Question

I'm using Bottle framework and need to open a excel spreadsheet..

Im wondering what should be the content-type on my return parameters

ie;

response.headers['Content-Type'] = 'text/html; charset=UTF-8'

My Current code-

@app.route('/SimpleCSV',method='GET')
def createxls():
   import xlsxwriter
    workbook = xlsxwriter.Workbook('hello.xlsx')
    worksheet = workbook.add_worksheet()
    worksheet.write('A1','HelloWorld')
    workbook.close()
    return workbook

New Code

    import StringIO
    import xlsxwriter
    output = StringIO.StringIO()

    workbook = xlsxwriter.Workbook(output, {'in_memory':True})
    worksheet = workbook.add_worksheet()
    worksheet.write(0,0,'Hello World')
    workbook.close()

    output.seek(0)

    print 'Excel file created and now will be returned'
    #response.headers['Content-Type'] = 'text/csv; charset=UTF-8'
    response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'
    response.headers['Content-Disposition'] = 'attachment; filename=text.xls'
    f1 = open('text-xls','w')
    f1.write(output.read())

    return

How do I open my excel file? Should it be f1 = open('test.xls') and write into it?

working code

@bottle.route('/xl')
def create_xls():
    import StringIO
    import xlsxwriter
    output = StringIO.StringIO()

    workbook = xlsxwriter.Workbook(output, {'in_memory':True})
    worksheet = workbook.add_worksheet()
    for each in range(100):
        for each1 in range(100):
                worksheet.write(each,each1,"Test")
    workbook.close()

    output.seek(0)

    response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'
    response.headers['Content-Disposition'] = 'attachment; filename=text1.xlsx'
    return output.read()
Was it helpful?

Solution

According to this and other sources, the content-type for Excel files is application/vnd.ms-excel for .xls files or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for .xlsx files.

But... from your Bottle route I'm wondering whether you're intending to return a csv file, in which case use text/csv.

Furthermore, (I think) you need to serialize workbook to bytes (a string) before returning it. Bottle does not know how to return a Workbook object. (Unless xlsxwriter.Workbook exposes an iterator that serializes it to a csv string, which seems unlikely.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top