From abf03bd4d6efca52d49a1dcbeef20b562107afad Mon Sep 17 00:00:00 2001 From: suti7yk5032 Date: Mon, 8 Jul 2024 11:23:19 +0900 Subject: [PATCH] =?UTF-8?q?Excel=E3=82=B7=E3=83=BC=E3=83=88=E3=81=A7?= =?UTF-8?q?=E5=87=BA=E5=8A=9B=E3=81=A7=E3=81=8D=E3=82=8B=E3=82=88=E3=81=86?= =?UTF-8?q?=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dislocker.py | 44 +++++++++++++++++------- temp/xcel.py | 97 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 129 insertions(+), 12 deletions(-) create mode 100644 temp/xcel.py diff --git a/dislocker.py b/dislocker.py index b51be28..05dfbc1 100644 --- a/dislocker.py +++ b/dislocker.py @@ -6,8 +6,8 @@ from psycopg2 import sql import hashlib import string import random -import csv from datetime import datetime +from openpyxl import Workbook class DL(): def __init__(self): @@ -203,6 +203,7 @@ class Bot(discord.Client): csv_file_path = dislocker.export_dir_path + "pc_usage_history.csv" main_table = "pc_usage_history" related_table = "club_member" + excel_file_path = dislocker.export_dir_path + "pc_usage_history.xlsx" # メインテーブルの列情報を取得(user_idを除く) cursor.execute(sql.SQL("SELECT * FROM {} LIMIT 0").format(sql.Identifier(main_table))) @@ -227,17 +228,36 @@ class Bot(discord.Client): rows = cursor.fetchall() - with open(csv_file_path, 'w', newline='', encoding='utf-8-sig') as csvfile: - csvwriter = csv.writer(csvfile) - csvwriter.writerow(column_names) - - for row in rows: - # nameを2番目に移動 - formatted_row = [self.format_datetime(row[0])] + [row[-1]] + [self.format_datetime(field) if field is not None else '' for field in row[1:-1]] - csvwriter.writerow(formatted_row) - - print(f"テーブル '{main_table}' の内容を '{csv_file_path}' に出力しました。") - result = {"result": "ok", "file_path": csv_file_path} + # Excelワークブックを作成 + wb = Workbook() + ws = wb.active + + # 列名を書き込み + ws.append(column_names) + + # データを書き込み + for row in rows: + # nameを2番目に移動 + formatted_row = [self.format_datetime(row[0])] + [row[-1]] + [self.format_datetime(field) if field is not None else '' for field in row[1:-1]] + ws.append(formatted_row) + + # 列幅を自動調整 + for col in ws.columns: + max_length = 0 + column = col[0].column_letter + for cell in col: + try: + if len(str(cell.value)) > max_length: + max_length = len(str(cell.value)) + except: + pass + adjusted_width = (max_length + 2) * 1.2 + ws.column_dimensions[column].width = adjusted_width + + # Excelファイルを保存 + wb.save(excel_file_path) + + print(f"テーブル '{main_table}' の内容を '{excel_file_path}' に出力しました。") except (Exception, psycopg2.Error) as error: print("使用履歴のエクスポート時にエラーが発生しました\nエラー内容\n", str(error)) diff --git a/temp/xcel.py b/temp/xcel.py new file mode 100644 index 0000000..684cfc7 --- /dev/null +++ b/temp/xcel.py @@ -0,0 +1,97 @@ +import psycopg2 +import csv +from psycopg2 import sql +from datetime import datetime +from openpyxl import Workbook +from openpyxl.utils import get_column_letter + +def format_datetime(value): + if isinstance(value, datetime): + return value.strftime('%Y-%m-%d %H:%M:%S') + return value + +def export_table_to_excel(host, port, database, user, password, main_table, related_table, excel_file_path): + try: + conn = psycopg2.connect( + host=host, + port=port, + database=database, + user=user, + password=password + ) + + cur = conn.cursor() + + # メインテーブルの列情報を取得(member_idを除く) + cur.execute(sql.SQL("SELECT * FROM {} LIMIT 0").format(sql.Identifier(main_table))) + main_columns = [desc[0] for desc in cur.description if desc[0] != 'member_id'] + + # クエリを作成(列名を明確に指定) + query = sql.SQL(""" + SELECT {main_columns}, {related_table}.name + FROM {main_table} + LEFT JOIN {related_table} ON {main_table}.member_id = {related_table}.id + """).format( + main_columns=sql.SQL(', ').join([sql.SQL("{}.{}").format(sql.Identifier(main_table), sql.Identifier(col)) for col in main_columns]), + main_table=sql.Identifier(main_table), + related_table=sql.Identifier(related_table) + ) + + cur.execute(query) + + # 列名を再構成(nameを2番目に配置) + column_names = [main_columns[0], 'name'] + main_columns[1:] + + rows = cur.fetchall() + + # Excelワークブックを作成 + wb = Workbook() + ws = wb.active + + # 列名を書き込み + ws.append(column_names) + + # データを書き込み + for row in rows: + # nameを2番目に移動 + formatted_row = [format_datetime(row[0])] + [row[-1]] + [format_datetime(field) if field is not None else '' for field in row[1:-1]] + ws.append(formatted_row) + + # 列幅を自動調整 + for col in ws.columns: + max_length = 0 + column = col[0].column_letter + for cell in col: + try: + if len(str(cell.value)) > max_length: + max_length = len(str(cell.value)) + except: + pass + adjusted_width = (max_length + 2) * 1.2 + ws.column_dimensions[column].width = adjusted_width + + # Excelファイルを保存 + wb.save(excel_file_path) + + print(f"テーブル '{main_table}' の内容を '{excel_file_path}' に出力しました。") + + except (Exception, psycopg2.Error) as error: + print("エラーが発生しました:", error) + + finally: + if conn: + cur.close() + conn.close() + print("データベース接続を閉じました。") + +# 使用例 +host = "192.168.1.220" +port = "12245" +database = "dislocker" +user = "suti7" +password = "Testing1234" +main_table = "pc_usage_history" +related_table = "club_member" +excel_file_path = "output.xlsx" + +export_table_to_excel(host, port, database, user, password, main_table, related_table, excel_file_path)