一つのファイルからクライアントごとの報告書を作成。
これまではエクセルでひとつひとつ処理していましたが、
書籍とネットで情報を集めた結果、pythonを使って以下のコードでできるようになりました。
30分かかっていた日々の作業がボタン一つで完了します!
感動しました。
はじめてのプログラミングにしては上出来です。
import pandas as pd
from datetime import datetime, timedelta
import os
import xlwings as xw
import datetime
samppath = "受注リスト.xlsx"
temppath = "報告書フォーマット.xlsx"
export_file = "(受注報告)"
item_code = "商品.xlsx"
d = datetime.datetime.now()
bar = "_"
pd.set_option('display.max_columns', 15)
df = pd.read_excel(samppath)
#データの取得
columns = df.iloc[2, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]]
df = df.iloc[3:1300, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]]
df.columns = columns
#ISBN挿入
df_item = pd.read_excel(item_code)
columns = df_item.iloc[: , [0, 1]]
df = df.merge(df_item, on='商品コード', how='left')
#不要な列を削除
df = df.iloc[:, [0, 2, 3, 4, 6, 7, 15, 9, 10, 11, 12, 13, 14]]
#並び替え
df = df.sort_values(by='取引先', ascending=False)
#置換
df["受注日"] = pd.to_datetime(df["受注日"]).dt.strftime("%Y-%m-%d")
df["作業コード"] = df["作業コード"].replace(1, "aaa")
df["作業コード"] = df["作業コード"].replace(2, "bbb")
df["作業コード"] = df["作業コード"].replace(3, "ccc")
df["備考"] = df["備考"].str.replace(" ", "")
df["備考"] = df["備考"].str.replace(" ", "")
df["備考"] = df["備考"].str.replace("、", "・")
torihiki_list = sorted(list(df["顧客名"].unique()))
App = xw.App()
for torihiki in torihiki_list:
wb = App.books.open(temppath)
ws = wb.sheets("報告書")
goukei = 0
gyo = 6
#変数filteredに「取引先」列を各取引先でフィルターしたデータを入れる
#filtered(pandasデータ)をリスト型へ変換して、valuesとする
filterd = df[df["顧客名"] == f"{torihiki}"]
values = filterd.values.tolist()
for rows in values:
for x, cell in enumerate(rows):
if x == 0:
ws.range(gyo, 2+x).value = cell
elif x == 1:
ws.range(gyo, 2+x).value =cell
elif x == 2:
ws.range(gyo, 2+x).value =cell
elif x == 3:
ws.range(gyo, 2+x).value =cell
elif x == 4:
ws.range(gyo, 2+x).value =cell
elif x == 5:
ws.range(gyo, 2+x).value =cell
elif x == 6:
ws.range(gyo, 2+x).value =cell
elif x == 7:
ws.range(gyo, 2+x).value =cell
elif x == 8:
ws.range(gyo, 2+x).value =cell
elif x == 9:
ws.range(gyo, 2+x).value =cell
elif x == 10:
ws.range(gyo, 2+x).value =cell
elif x == 11:
ws.range(gyo, 2+x).value =cell
elif x == 12:
ws.range(gyo, 2+x).value =cell
elif x == 13:
ws.range(gyo, 2+x).value =cell
elif x == 14:
ws.range(gyo, 2+x).value =cell
elif x == 15:
ws.range(gyo, 2+x).value =cell
gyo += 1
filename = d.strftime('%Y%m%d') + bar + torihiki + export_file + ".xlsx"
wb.save(filename)
wb.close()
App.quit()
#報告不要なクライアントのファイルを削除
cliants = [str(d.strftime('%Y%m%d') + bar + "クライアントC" + export_file + ".xlsx"),
str(d.strftime('%Y%m%d') + bar + "クライアントF" + export_file + ".xlsx"),
str(d.strftime('%Y%m%d') + bar + "クライアントS" + export_file + ".xlsx"),
str(d.strftime('%Y%m%d') + bar + "クライアントU" + export_file + ".xlsx"),
for i in cliants:
if os.path.exists(i):
os.remove(i)
else:
continue