Home » excel » excel – xlrd,xlwt in python (how to copy an entire row)

excel – xlrd,xlwt in python (how to copy an entire row)

Posted by: admin May 14, 2020 Leave a comment

Questions:

Ideally i am copying an entire row from another excel worksheet. So instead of showing that code, my problem starts from when i have that row in a list, how do i put it in another excel worksheet now? I want it to look exactly the same. Goal: Take either of the data formats, and putting them in a blank excel worksheet in e.g. row 1. I would like this to be something fast, since i plan to scale it up to 10,000 rows.

Data can be in either format:

data = [number:6842.0, xldate:41771.0, xldate:0.005555555555555556,
        text:u'Hello World']
data = [6842.0, 41771.0, 0.005555555555555556, u'Hello World']

My Code:

import xlwt
wb = xlwt.Workbook()
data = [6842.0, 41771.0, 0.005555555555555556, u'Hello World'] #either format
sheet1 = wb.add_sheet("MyData")
sheet1.write(1,0,data)
wb.save('C:\Python27\helloworld.xls')

This is how i am grabbing my data from an excel file:

from xlrd import *
import xlwt

book = open_workbook(filename= 'C:\Users\ssheikh\Desktop\CopyFile.xls')
sh = book.sheet_by_index(0)
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("MyData")

b = xldate.xldate_from_date_tuple((2014,5,12), 0) 
c = xldate.xldate_from_date_tuple((2014,5,13), 0)

mylist = []
listc = []
listd = []
for i in xrange(0,sh.nrows):
    if sh.cell_value(rowx=i, colx =1) == b:
        mylist.append(i)
        listd.append(sh.row_values(i))
        print 'the number', b ,'was found in row=', i, 'and column =0'


    if sh.cell_value(rowx=i,colx =1) == c:
        listc.append(i)
        listd.append(sh.row(i))

#mylist[0] #upper limit of my rows
#listc[-1] #lower limit of my rows
listd # this has all of my rows that i want to put in a new excel file
How to&Answers:

I don’t see any write_row method in xlwt like there is row_values in xlrd. There is only sheet.write of the Worksheet object of or write_rich_text if need be.

for row_index, row in enumerate(listd):
   for col_index, cell_value in enumerate(row):
       sheet.write(row_index, col_index, cell_value)
workbook.save("myData.xls")

If there are special styles you can use the optional style argument of write.