内容类型xls for Bottle框架

时间:2014-04-04 18:53:39

标签: excel bottle

我使用的是Bottle框架,需要打开一个excel电子表格。

我想知道返回参数的内容类型应该是什么

即;

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

我当前的代码 -

@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

新代码

    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

如何打开我的Excel文件?应该是f1 = open(' test.xls')并写入它?

工作代码

@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()

1 个答案:

答案 0 :(得分:1)

根据this和其他来源,Excel文件的内容类型对于.xls文件为application/vnd.ms-excel,对于.xlsx文件为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

但是......从你的瓶子路线我想知道你是否打算返回一个csv文件,在这种情况下使用text/csv

此外,(我认为)您需要在返回之前将workbook序列化为字节(字符串)。 Bottle不知道如何返回Workbook个对象。 (除非xlsxwriter.Workbook公开一个将它序列化为csv字符串的迭代器,这似乎不太可能。)