In my day-to-day work, I frequently use pandas to analyze and manipulate data, then output the results in Excel. The next step in the process is to open up the Excel and review the results. In this example, we can automate the file opening process which can make it simpler than trying to navigate to the right directory and open a file.
Here's the full example:
import win32com.client as win32
import pandas as pd
from pathlib import Path
# Read in the remote data file
df = pd.read_csv("https://github.com/chris1610/pbpython/blob/master/data/sample-sales-tax.csv?raw=True")
# Define the full path for the output file
out_file = Path.cwd() / "tax_summary.xlsx"
# Do some summary calcs
# In the real world, this would likely be much more involved
df_summary = df.groupby('category')['ext price', 'Tax amount'].sum()
# Save the file as Excel
df_summary.to_excel(out_file)
# Open up Excel and make it visible
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True
# Open up the file
excel.Workbooks.Open(out_file)
# Wait before closing it
_ = input("Press enter to close Excel")
excel.Application.Quit()
Here's the resulting Excel output:
This simple example expands on the earlier one by showing how to use the Workbooks
object to open up a file.
Comments