やりたいこと
- GCP StorageからExcelファイル読込
- Excel内容変更
- GCP StorageにExcelファイル書込
- ファイルダウンロード
Example
# -*- coding: utf-8 -*-
import logging
from flask import render_template, Flask, Response
from google.cloud import storage
import openpyxl
from openpyxl.writer.excel import save_virtual_workbook
import io
app = Flask(__name__)
logging.getLogger().setLevel(logging.INFO)
@app.route('/applicationform/a0026', methods=['GET', 'POST'])
def a0026():
client = storage.Client()
bucket = client.get_bucket('★プロジェクト名★.appspot.com')
blob = bucket.blob('a0025.xlsx')
blob_io = io.BytesIO(blob.download_as_string())
wb = openpyxl.load_workbook(blob_io, keep_vba=False)
sheet = wb.get_sheet_by_name('★シート名★')
sheet['K5'] = 'Test Test'
save_data = save_virtual_workbook(wb)
new_blob = bucket.blob('a0025_new.xlsx')
new_blob.upload_from_string(save_data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
res = Response(save_data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
res.headers['Content-Disposition'] = 'attachment; filename="a0025_new.xlsx"'
return res
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
マクロ有のファイルの場合
keep_vbaをTrueにする。
wb = openpyxl.load_workbook(blob_io, keep_vba=True)
Content-Type「application/vnd.ms-excel.sheet.macroEnabled.12」に変更
new_blob.upload_from_string(save_data, content_type='application/vnd.ms-excel.sheet.macroEnabled.12')
res = Response(save_data, content_type='application/vnd.ms-excel.sheet.macroEnabled.12')
拡張子変更
new_blob = bucket.blob('a0025_new.xlsm')
res.headers['Content-Disposition'] = 'attachment; filename="a0025_new.xlsm"'
#memo
- Excel処理はOpenPyXL使用