2017-03-22 13 views
0

openpyxlを使用してExcelファイルを作成していますが、これはファイルのダウンロードとして戻したいので(ローカルには保存しません)。フラスコで作成したExcelファイルを返す

私は、Excelファイルをきれいに作成してディスクに保存できます。しかし、私はこのファイルをダウンロードすることができません。

試み1: WB = create_excel_sheet(データ)#戻りopenpyxlブック

output = excel.make_response(wb) 
output.headers["Content-Disposition"] = "attachment; filename=" + \ 
             'sheet.xlsx' 
output.headers["Content-type"] = "application/vnd.openxmlformats-\ 
officedocument.spreadsheetml.sheet" 

return output 

import flask_excel as excel 

... 

create_excel_sheet(data) # internally save the sheet with name sheet.xlsx 

output = excel.make_response() 
output.headers["Content-Disposition"] = "attachment; filename=" + \ 
             'sheet.xlsx' 
output.headers["Content-type"] = "application/vnd.openxmlformats-\ 
officedocument.spreadsheetml.sheet" 

return output 

これは名前sheet.xlsx

試み2と空のテキストファイルを返します私は、空白のExcelシートを作成するためにopenpyxlが必要なので、データにpyexcelを使用したくありません。明らかにpyexcelとopenpyxlが通信していればそれは問題ありません。

どのような考えですか?

乾杯、私は同じ問題に直面したとき、私が何をしたかマイク

+0

openpyxlは ' –

+0

)あなたは(save_virtual_workbook'を持つオブジェクトのようなファイルに保存することができない

output = make_response(create_sheet(data)) output.headers["Content-Disposition"] = "attachment; filename=" + \ "sheet.xlsx" output.headers["Content-type"] = \ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" 

!おかげで – Mike

答えて

1

、私は最終的には、以下のソリューションで解決しました。それだ

def create_sheet(data): 

戻り

return save_virtual_workbook(wb) 
1

は、私は、サーバー上の一時ファイルを書いて、私は、ファイル名を返すために、私のcreate_excel_sheet(data)機能を作った後、フラスコに戻ってファイルを送信することであるsend_file()機能:

send_file(create_excel_sheet_and_return_filename(data)) 

あなたは、プロセスが存在する場合に削除される一時ファイルを作成するPythonモジュールを使用して、セキュリティが問題であれば、許可を使用することができます。

+0

ありがとう!これはうまくいくようですが、私の一時ファイルは/ tmp/dirに追加されています。私はこのアプローチを次のように使用しました:http://stackoverflow.com/questions/31391344/using-tempfile-to-create-pdf-xls-documents-in-flask – Mike

+0

名前付きテンポラリファイルをdelete = Trueで作成しましたか? https://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile – grepe

0

すべてと思われる。あなたは実際にあなたの見解から応答を返していますか?それは問題ではっきりしておらず、問題を説明すると思います。例えば

:チャーリー・クラークのヒントをもとに

@app.route('/download_sheet') 
def download(): 
    create_excel_sheet(data) 
    output = excel.make_response() 
    output.headers["Content-Disposition"] = "attachment; filename=sheet.xlsx" 
    output.headers["Content-type"] = "application/vnd.openxmlformats-\ 
officedocument.spreadsheetml.sheet" 
    return output # Send the response to the user 

...

<a href="{{ url_for('app.download') }}">Click here for Sheet</a> 
+1

私は出力を返します(上記で編集しました)。私の問題(今)は、一時的なもので私の記憶を埋めることなくファイルを返すことです – Mike

+0

Hm - 一時ファイルの解決策が働いているようです。ですから、あなたはアプリが定期的に一時ファイルを検索して削除するようにしてはいかがですか? –

関連する問題