Home » excel » How to copy a row of Excel sheet to another sheet using Python

How to copy a row of Excel sheet to another sheet using Python

Posted by: admin April 23, 2020 Leave a comment


I want to compare the value of a given column at each row against another value, and if the values are equal, I want to copy the whole row to another spreadsheet.

How can I do this using Python?


How to&Answers:

pls refer to python excel library xlrd(for excel reading)/xlwt(for excel writing)

for example(reading)(from this):

import xlrd

fname = "sample.xls"
bk = xlrd.open_workbook(fname)
shxrange = range(bk.nsheets)
    sh = bk.sheet_by_name("Sheet1")
    print "no sheet in %s named Sheet1" % fname
    return None
nrows = sh.nrows
ncols = sh.ncols
print "nrows %d, ncols %d" % (nrows,ncols)

cell_value = sh.cell_value(1,1)
print cell_value

row_list = []
for i in range(1,nrows):
    row_data = sh.row_values(i)

if you are handling with Excel 2007 , then use openpyxl : http://packages.python.org/openpyxl/


For “xls” files it’s possible to use the xlutils package. It’s currently not possible to copy objects between workbooks in openpyxl due to the structure of the Excel format: there are lots of dependencies all over the place that need to be managed. It is, therefore, the responsibility of client code to copy everything required manually. If time permits we might try and port some of the xlutils functionality to openpyxl.