|
| 1 | + |
| 2 | +import win32com.client as win32 |
| 3 | + |
| 4 | +def clear_pts(ws): |
| 5 | + for pt in ws.PivotTables(): |
| 6 | + pt.TableRange2.Clear() |
| 7 | + |
| 8 | +def insert_pt_filed_set1(pt): |
| 9 | + field_rows={} |
| 10 | + field_rows['Customer code']=pt.PivotFields("Customer Code") |
| 11 | + field_rows['Customer']=pt.PivotFields("Customer") |
| 12 | + |
| 13 | + field_values={} |
| 14 | + field_values['total']=pt.PivotFields("Amount") |
| 15 | + |
| 16 | + field_filter={} |
| 17 | + field_filter["filter"]=pt.PivotFields("G/L Account") |
| 18 | + |
| 19 | + filed_column={} |
| 20 | + filed_column['age']=pt.PivotFields("aging") |
| 21 | + |
| 22 | + field_rows['Customer code'].Orientation=1 |
| 23 | + field_rows['Customer code'].Position=1 |
| 24 | + |
| 25 | + field_rows['Customer'].Orientation=1 |
| 26 | + field_rows['Customer'].Position=2 |
| 27 | + |
| 28 | + #insert data fileds |
| 29 | + field_values['total'].Orientation=4 |
| 30 | + field_values['total'].Function=-4157#-4112 |
| 31 | +## field_values['total'].NumerFormat="#,##0" #for sum function- -4157 |
| 32 | + |
| 33 | + #inserting filter |
| 34 | + field_filter["filter"].Orientation=3 |
| 35 | + |
| 36 | + #inserting column |
| 37 | + filed_column['age'].Orientation=2 |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | +# Open the Excel file |
| 43 | +xlapp = win32.gencache.EnsureDispatch('Excel.Application') |
| 44 | +xlapp.Visible=True |
| 45 | +wb = xlapp.Workbooks.Open(r"D:\BASIC_Tech\Excel_python\pivot_table_win32.xlsx") |
| 46 | +ws = wb.Sheets('Sheet1') |
| 47 | +ws_report=wb.Worksheets("report") |
| 48 | +clear_pts(ws_report) |
| 49 | +### Create a pivot table |
| 50 | +pt_cache=wb.PivotCaches().Create(1,ws.Range("A1").CurrentRegion) |
| 51 | +pt=pt_cache.CreatePivotTable(ws_report.Range("B3"),"My_report summary") |
| 52 | + |
| 53 | +pt.ColumnGrand=True |
| 54 | +pt.RowGrand=True |
| 55 | + |
| 56 | + |
| 57 | +##pt.SubtotalLocation(1) |
| 58 | +pt.RowAxisLayout(1) |
| 59 | +pt.PivotFields('Customer Code').Subtotals = tuple(False for _ in range(12)) |
| 60 | +#chnage pivot table style |
| 61 | +pt.TableStyle2="PivotStyleMedium9" |
| 62 | + |
| 63 | +#creating report |
| 64 | +insert_pt_filed_set1(pt) |
| 65 | + |
| 66 | + |
| 67 | +wb.Save() |
| 68 | +xlapp.Application.Quit() |
| 69 | +## |
0 commit comments