Pythonで作成したExcel検索・編集ツールのGUI部分をFlaskを使ってWebアプリケーションにすることもできます。
Flaskは軽量なWebフレームワークで、PythonでのWebアプリ開発を行うことができます。
以下に、先日作成したツールと同様の機能をFlaskで実装する手順を説明します。
主な流れは、キーワード検索、Excel行の選択、編集、更新/追加処理をWebインターフェースで実装です。
構成する機能
- Excelファイルのアップロード: ユーザーがExcelファイルをWeb上でアップロードし、サーバー側でそのファイルを操作します。
- キーワード検索: アップロードされたExcelファイルから指定のキーワードを検索し、該当する行をリスト表示します。
- 行の編集・追加: 検索結果から選択された行をWebフォームに表示し、編集や新規行の追加を行います。
- 更新と保存: 編集内容をコピーされたExcelファイルに反映します。
必要なライブラリ
まず、必要なライブラリをインストールします。
pip install flask openpyxl
Flaskアプリケーションのコード例
from flask import Flask, render_template, request, redirect, url_for, flash, send_file
from openpyxl import load_workbook
import os
import shutil
app = Flask(__name__)
app.secret_key = 'secret'
# 一時的にExcelファイルを保存するディレクトリ
UPLOAD_FOLDER = '[アプリを格納するフォルダへのパスを設定]\\uploads'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
# グローバル変数
excel_file_path = None
copied_file_path = None
ws = None
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
global excel_file_path, ws, copied_file_path
if 'file' not in request.files:
flash('ファイルが見つかりません', 'error')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('ファイルが選択されていません', 'error')
return redirect(request.url)
if file and file.filename.endswith('.xlsx'):
# ファイルを一時保存
file_path = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(file_path)
# コピーを作成
excel_file_path = file_path
copied_file_path = os.path.splitext(excel_file_path)[0] + "_copy.xlsx"
shutil.copyfile(excel_file_path, copied_file_path)
# Excelファイルを読み込み
workbook = load_workbook(copied_file_path)
ws = workbook.active
flash('ファイルが正常にアップロードされました', 'success')
return redirect(url_for('search'))
flash('無効なファイル形式です。Excelファイル(.xlsx)をアップロードしてください', 'error')
return redirect(request.url)
@app.route('/search', methods=['GET', 'POST'])
def search():
global ws, copied_file_path
results = []
if request.method == 'POST':
keyword = request.form.get('keyword')
if keyword:
# キーワードでExcelのデータを検索
for row_index, row in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2):
for cell in row:
if cell and keyword in str(cell):
results.append((row_index, row)) # 行インデックスと行データを保存
return render_template('search.html', results=results)
@app.route('/edit/', methods=['GET', 'POST'])
def edit(row_index):
global ws, copied_file_path
if request.method == 'POST':
new_data = request.form.get('data')
if new_data:
# 更新処理
updated_values = new_data.split(',')
for col, value in enumerate(updated_values, 1):
ws.cell(row=row_index, column=col, value=value.strip())
ws.parent.save(copied_file_path) # コピーされたExcelファイルに保存
flash(f"行 {row_index} が更新されました", 'success')
return redirect(url_for('search'))
# 編集対象の行データを取得
row_data = [cell.value for cell in ws[row_index]]
return render_template('edit.html', row_data=row_data, row_index=row_index)
@app.route('/add', methods=['GET', 'POST'])
def add():
global ws, copied_file_path
if request.method == 'POST':
new_data = request.form.get('data')
if new_data:
# 新規行を追加
new_row = new_data.split(',')
ws.append([value.strip() for value in new_row])
ws.parent.save(copied_file_path) # コピーされたExcelファイルに保存
flash("新しい行が追加されました", 'success')
return redirect(url_for('search'))
return render_template('add.html')
@app.route('/download')
def download():
global ws
return send_file(ws.parent.filename, as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)
テンプレートファイル
FlaskではHTMLテンプレートを使ってWebページを表示します。テンプレートを保存するディレクトリはtemplatesです。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Excel 検索&編集ツール</title>
</head>
<body>
<h1>Excel 検索&編集ツール</h1>
<form action="{{ url_for('upload_file') }}" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="アップロード">
</form>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul>
{% for category, message in messages %}
<li class="{{ category }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</body>
</html>
search.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>キーワード検索</title>
</head>
<body>
<h1>キーワード検索</h1>
<form action="{{ url_for('search') }}" method="post">
<input type="text" name="keyword">
<input type="submit" value="検索">
</form>
{% if results %}
<ul>
{% for row_index, row in results %}
<li>{{ row }} <a href="{{ url_for('edit', row_index=row_index) }}">編集</a></li>
{% endfor %}
</ul>
{% endif %}
<a href="{{ url_for('add') }}">新しい行を追加</a>
</body>
</html>
edit.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>編集</title>
</head>
<body>
<h1>行の編集</h1>
<form action="{{ url_for('edit', row_index=row_index) }}" method="post">
<input type="text" name="data" value="{{ row_data | join(', ') }}">
<input type="submit" value="更新">
</form>
</body>
</html>
add.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>新しい行を追加</title>
</head>
<body>
<h1>新しい行を追加</h1>
<form action="{{ url_for('add') }}" method="post">
<input type="text" name="data" placeholder="カンマ区切りで入力">
<input type="submit" value="追加">
</form>
</body>
</html>
ファイルの基本構成
project_root/
│
├── app.py # Flaskアプリケーション本体
├── uploads/ # ユーザーがアップロードするファイルの保存先
│ └── example.xlsx # アップロードされたファイルの例
├── templates/ # HTMLテンプレート
│ ├── index.html # ファイルアップロード用のページ
│ ├── search.html # キーワード検索用のページ
│ ├── edit.html # Excelの行編集用のページ
│ └── add.html # 新しい行を追加するページ
└── static/ # 静的ファイル(CSSやJSファイル)
└── style.css # デザイン用のスタイルシート
実行方法
app.pyが存在するディレクトリで以下のコマンドを実行して、Flaskアプリケーションを起動します。
python app.py
- Webブラウザで
http://127.0.0.1:5000にアクセスすると、アプリケーションのトップページ(ファイルアップロード画面)が表示されます。
動作の流れ
- ユーザーは
index.htmlでExcelファイルをアップロードします。 search.htmlでキーワード検索を行い、該当する行を表示します。- 検索結果の行をクリックすると、その行を編集できる
edit.htmlに移動します。 add.htmlから新しい行を追加することもできます。- 最後に、変更・追加された内容はダウンロードすることも可能です。
まとめ
このコードを使って、Pythonで作成したExcel検索・編集ツールをWebアプリとして実装できます。
Flaskを使うことで、ローカルアプリケーションからWebアプリケーションに拡張することができ、他のユーザーとも簡単に共有できるようになります。





コメント