In python removing rows from a excel file using xlrd, xlwt, and xlutils

user2105494 picture user2105494 · May 17, 2013 · Viewed 13.3k times · Source

Hello everyone and thank you in advance.

I have a python script where I am opening a template excel file, adding data (while preserving the style) and saving again. I would like to be able to remove rows that I did not edit before saving out the new xls file. My template xls file has a footer so I want to delete the extra rows before the footer.

Here is how I am loading the xls template:

self.inBook = xlrd.open_workbook(file_path, formatting_info=True)
self.outBook = xlutils.copy.copy(self.inBook)
self.outBookCopy = xlutils.copy.copy(self.inBook)

I then write the info to outBook while grabbing the style from outBookCopy and applying it to each row that I modify in outbook.

so how do I delete rows from outBook before writing it? Thanks everyone!

Answer

Jd16 picture Jd16 · Jan 6, 2016

I achieved using Pandas package....

import pandas as pd

#Read from Excel
xl= pd.ExcelFile("test.xls")

#Parsing Excel Sheet to DataFrame
dfs = xl.parse(xl.sheet_names[0])

#Update DataFrame as per requirement
#(Here Removing the row from DataFrame having blank value in "Name" column)

dfs = dfs[dfs['Name'] != '']

#Updating the excel sheet with the updated DataFrame

dfs.to_excel("test.xls",sheet_name='Sheet1',index=False)