Using xlwings and pandas we will learn how to open, manipulate and save the MS Excel file in Python. This is a reference material for experienced programmers.
Working with Microsoft Excel Files
► Import the modules required to work with Excel file.
import xlwings as xw
import pandas as pd
from collections import defaultdict
► Specify the Excel file name (and not the path).
► Get the path of the directory separately in a different variable.
► Alternatively you can also specify the full path and pass it directly to the Book method.
excelName = "MyExcel.xlsx"
workingDir = "C:\MyApp\MyFolder" # no slash in the end
# Join method of os module can be used to join the paths and create a full path
# And read the whole Excel file and the created object is 'reportExcel'
reportExcel = xw.Book(os.path.join(workingDir, excelName))
app = xw.apps.active # it seems this opens the Excel file
Make the necessary changes to the file
► Add a single value to a specific Cell using its row and column position
row_index = 1 # Second row in the Excel, first row starts with zero
col_index = 1 # First column of the Excel
reportExcel.sheets('Results').range(row_index, col_index).value = "12.12"
► Add a collection of rows and columns (i.e. a table) to the Excel sheet
# Assume you have a Employee DataFrame named - df
# Below line will add this DataFrame to the Excel starting from the E1 Cell
reportExcel.sheets('Connection Report').range('e1').value = df
► Add a column to the Excel sheet
# All the Employee names will be added to the column B2 of 'Report' Excel sheet - assume that the emp_names is a pandas Series
reportExcel.sheets('Report').range('b2').options(transpose=True).value = emp_names
Finally save and close the Excel file
reportExcel.save(path=workingDir + r'MyFile.xlsx')
app.quit() # this will close the opened Excel file
sys.exit(0)
Summary
This post provides a quick reference to manipulate Microsoft Excel file in Python.
Your feedback
Your feedback is of paramount importance to us, provide your valuable inputs; what else you would like to read about, or if you would like the author to elaborate on any specific topic from this article, or any other article on this blog.
Disclaimer
The material presented in this blog is to help educate the developers, and the author(s) & owner(s) of this blog are not responsible of any damage arising out of use of the code snippets or any other contents of this blog.
Comments
Post a Comment