Edit Excel from Python to create a PivotTable

I want to improve efficiency using Python

To improve work efficiency, I wanted to create a pivot table for an Excel file created in Pandas, enable filters, and group dates and times.

I didn't have much material in Japanese, so I would like to share it as a reference.

The URL shown in Reference shows a function to create a pivot table, so if you want to do more things, you should refer to that.

Creating a sample file

Create data for a pivot table that doesn't make any sense. Edit the file name to be output as an Excel file. Make sure that the specified file name is not in the same directory. We cannot take responsibility even if it is overwritten.

import pandas as pd 
import random
from datetime import datetime as dt

record = []
for y in range(2015, 2020):
    for m in range(1, 13):
        for shop in ['A', 'B', 'C']:
            date = dt(year=y, month=m, day=1).strftime('%Y-%m-%d')
            price = 200 + random.randint(0,100)    
            record.append([date, shop, price])

df_record = pd.DataFrame(record)
df_record.columns = ['date', 'shop', 'price']
df_record['date'] = pd.to_datetime(df_record['date'])
df_record.to_excel('Please edit here.xlsx', index=None)

Pivot table creation

Specify the file name specified in [Create sample file](#Create sample file) as the read file name.

import win32com.client as win32
import os
win32c = win32.constants

## win32.I could do it with Dispatch, but I got an error when I made it into an exe with pyinstaller, so
## win32.gencache.It may be safer to use EnsureDispatch
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True  

##If you do not specify the absolute path when reading, an error will occur
fpath = os.path.join(os.getcwd(),'Please edit here.xlsx')
wb = excel.Workbooks.Open(fpath)

##Specify Sheet 1 and enable the filter
wbs1 = wb.Sheets('Sheet1')
wbs1.Columns.AutoFilter(1)

##Creating a pivot table
wbs2_name = 'pivot'
wb.Sheets.Add().Name = wbs2_name
wbs2 = wb.Sheets(wbs2_name)
pvt_name = 'pvt'
pc = wb.PivotCaches().Create(SourceType=win32c.xlDatabase, SourceData=wbs1.UsedRange)
pc.CreatePivotTable(TableDestination='{sheet}!R3C1'.format(sheet=wbs2_name), TableName=pvt_name)

##Pivot table settings
wbs2.PivotTables(pvt_name).PivotFields('date').Orientation = win32c.xlRowField
wbs2.PivotTables(pvt_name).AddDataField(wbs2.PivotTables(pvt_name).PivotFields('price'), 'Ave/price', win32c.xlAverage).NumberFormat = '0'
wbs2.PivotTables(pvt_name).PivotFields('price').Orientation = win32c.xlPageField

##Date group selection
## Periods=(Seconds,Minutes,Time,Day,Month,quarter,Year)
wbs2.Cells(4, 1).Select()
excel.Selection.Group(Start=True, End=True, Periods=(False, False, False, False, True, False, True))

##Close file
wb.Close(True)
excel.Quit()

Reference material

How to Create a Pivot Table in Excel with the Python win32com Module

Recommended Posts

Edit Excel from Python to create a PivotTable
Create a C array from a Python> Excel sheet
Python script to create a JSON file from a CSV file
How to create a kubernetes pod from python code
Create folders from '01' to '12' with python
5 Ways to Create a Python Chatbot
How to create a clone from Github
Send a message from Python to Slack
Create a deb file from a python package
How to create a repository from media
Create a dataframe from excel using pandas
Send a message from Slack to a Python server
[Python] List Comprehension Various ways to create a list
How to create a Python virtual environment (venv)
How to open a web browser from python
How to create a function object from a string
Create a Python module
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Import Excel file from Python (register to DB)
I want to create a window in Python
How to create a JSON file in Python
Create a tool to automatically furigana with html using Mecab from Python3
Create a New Todoist Task from Python Script
[python] Create table from pandas DataFrame to postgres
Run python from excel
How to generate a Python object from JSON
Steps to create a Twitter bot with python
Create a decision tree from 0 with Python (1. Overview)
Create a datetime object from a string in Python (Python 3.3)
Create a Python environment
Run a python script from excel (using xlwings)
Create a setting in terraform to send a message from AWS Lambda Python3.8 to Slack
Create a plugin to run Python Doctest in Vim (2)
Create a plugin to run Python Doctest in Vim (1)
Steps from installing Python 3 to creating a Django app
From buying a computer to running a program with python
Consider a conversion from a Python recursive function to a non-recursive function
[Python] How to create a 2D histogram with Matplotlib
[Python] How to call a c function from python (ctypes)
Create a Wox plugin (Python)
Post from Python to Slack
Create a function in Python
Create a dictionary in Python
Cheating from PHP to Python
A road to intermediate Python
Anaconda updated from 4.2.0 to 4.3.0 (python3.5 updated to python3.6)
Create a python numpy array
Switch from python2.7 to python3.6 (centos7)
Connect to sqlite from python
[Introduction to Python] <list> [edit: 2020/02/22]
Create a directory with python
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
[It's not too late to learn Python from 2020] Part 2 Let's create a Python development environment
How to create a radial profile from astronomical images (Chandra, XMM etc.) using python
How to use NUITKA-Utilities hinted-compilation to easily create an executable file from a Python script
I wrote Python code to create a table (view) dependency diagram (PlantUML) from SQL
I tried to create API list.csv in Python from swagger.yaml
How to slice a block multiple array from a multiple array in Python
How to run a Python program from within a shell script
Create a Mastodon bot with a function to automatically reply with Python