简体   繁体   中英

How to write a entire row in excel from an array - xlwt

I would like to improve my code, replacing this:

workbook = xlwt.Workbook()
sheet = workbook.add_sheet("WS") 

header = [u'Nome da estação',u'Altitude',u'Latitude',u'Longitude']

column =0
for h in header:
    sheet.write(0, column, h)
    column += 1

For some code to use directly the array header to write an entire line. Any idea?

You are unlikely to get any actual improvement from writing your data as a row unit because Excel stores cells individually either way. That is probably why there is no such method documented for xlwt .

You can cut your code down by a couple of lines by using enumerate:

workbook = xlwt.Workbook()
sheet = workbook.add_sheet("WS") 

header = [u'Nome da estação',u'Altitude',u'Latitude',u'Longitude']

for column, heading in enumerate(header):
    sheet.write(0, column, heading)

If you find yourself doing this sort of thing regularly, write a small utility method:

def write_header(header, row=0, start_col=0):
    for column, heading in enumerate(header, start_col):
        sheet.write(row, column, heading)

workbook = xlwt.Workbook()
sheet = workbook.add_sheet("WS") 

write_header([u'Nome da estação',u'Altitude',u'Latitude',u'Longitude'])

The additional parameters will allow you to set the upper-left corner of the header in the spreadsheet should you ever need to. The default values should cover 99% of use cases.

There's only sheet.write() , which writes for row_index, column_index .

If you're are worried about speed or optimization, just focus on optimizing the for loops, like you would for any other programming flow.

workbook.save() is required only once at the end -- so the file I/O still happens only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM