TheDarkLord69696969 commited on
Commit
83d8ca6
1 Parent(s): f763e99

Upload temp.py

Browse files
Files changed (1) hide show
  1. temp.py +66 -0
temp.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys # Standard Python Libraries
2
+ import xlwings as xw # pip install xlwings
3
+ from docxtpl import DocxTemplate # pip install docxtpl
4
+ import pandas as pd # pip install pandas
5
+ import matplotlib.pyplot as plt # pip install matplotlib
6
+ import win32com.client as win32 # pip install pywin32
7
+
8
+ # -- Documentation:
9
+ # python-docx-template: https://docxtpl.readthedocs.io/en/latest/
10
+
11
+ # Change path to current working directory
12
+ os.chdir(sys.path[0])
13
+
14
+
15
+ def create_barchart(df, barchart_name):
16
+ """Group DataFrame by sub-category, plot barchart, save plot as PNG"""
17
+ top_products = df.groupby(by=df["Sub-Category"]).sum()[["Sales"]]
18
+ top_products = top_products.sort_values(by="Sales")
19
+ plt.rcParams["figure.dpi"] = 300
20
+ plot = top_products.plot(kind="barh")
21
+ fig = plot.get_figure()
22
+ fig.savefig(f"{barchart_name}.png", bbox_inches="tight")
23
+ return None
24
+
25
+
26
+ def convert_to_pdf(doc):
27
+ """Convert given word document to pdf"""
28
+ word = win32.DispatchEx("Word.Application")
29
+ new_name = doc.replace(".docx", r".pdf")
30
+ worddoc = word.Documents.Open(doc)
31
+ worddoc.SaveAs(new_name, FileFormat=17)
32
+ worddoc.Close()
33
+ return None
34
+
35
+
36
+ def main():
37
+ wb = xw.Book.caller()
38
+ sht_panel = wb.sheets["PANEL"]
39
+ sht_sales = wb.sheets["Sales"]
40
+ doc = DocxTemplate("Copy of Last Will and Testament.docx")
41
+ # -- Get values from Excel
42
+ context = sht_panel.range("A2").options(dict, expand="table", numbers=int).value
43
+ df = sht_sales.range("A1").options(pd.DataFrame, index=False, expand="table").value
44
+
45
+ # -- Create Barchart & Replace Placeholder
46
+ barchart_name = "sales_by_subcategory"
47
+ create_barchart(df, barchart_name)
48
+ doc.replace_pic("Placeholder_1.png", f"{barchart_name}.png")
49
+
50
+ # -- Render & Save Word Document
51
+ output_name = f'Sales_Report_{context["month"]}.docx'
52
+ doc.render(context)
53
+ doc.save(output_name)
54
+
55
+ # -- Convert to PDF [OPTIONAL]
56
+ path_to_word_document = os.path.join(os.getcwd(), output_name)
57
+ convert_to_pdf(path_to_word_document)
58
+
59
+ # -- Show Message Box [OPTIONAL]
60
+ show_msgbox = wb.macro("Module1.ShowMsgBox")
61
+ show_msgbox("DONE!")
62
+
63
+
64
+ if __name__ == "__main__":
65
+ xw.Book("word_automation.xlsm").set_mock_caller()
66
+ main()