2

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?

5
  • 1
    for c, h in enumerate(header): sheet.write(0, c, h) is already an improvement. Commented May 1, 2017 at 0:41
  • Sure is a good improvement! Thanks! But I was thinking related to constructor of a row or something else related to write an array natively like a method of the sheet. Commented May 1, 2017 at 2:26
  • There does not appear to be such a method. Given the way that excel stores data in a cell-by-cell format, you probably wouldn't get much mileage out of such a method anyway. If you are just looking for the convenience of not typing as much, write your own utility method. Commented May 1, 2017 at 14:59
  • OK, I understood. Really, I didn't still found.Thank you! Commented May 1, 2017 at 15:14
  • I went ahead and posted an answer you you to select and updoot when you have time. Commented May 2, 2017 at 21:37

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.