Reputation: 2400
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?
Upvotes: 2
Views: 9293
Reputation: 5483
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.
Upvotes: 0
Reputation: 114330
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.
Upvotes: 5