0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GCP App Engine StorageのExcelファイル読込、内容変更、書込

Posted at

やりたいこと

  1. GCP StorageからExcelファイル読込
  2. Excel内容変更
  3. GCP StorageにExcelファイル書込
  4. ファイルダウンロード

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使用
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?