codeKiller
codeKiller

Reputation: 5739

Openpyxl: write cells with different format

I am writing an excel sheet. I want to write the header (with the names of the columns) and the data (float numbers with 2 decimal digits) with the same script.

To do this I am using this piece of code:

    # Write the header
    for i in xrange(len(header)):
        sheet.cell(row=1,column=i+1).value = header[i]

    # Write the data
    for i in xrange(len(data)):
        sheet.cell(row=2,column=i+1).style.number_format.format_code = '0.00E+00' 
        sheet.cell(row=2,column=i+1).value = float(data[i])

    book.save(os.path.join(folder,'excelReport.xlsx'))

This gives me en exception:

AttributeError: 'str' object has no attribute 'format_code'

I am not 100% sure of what I am doing wrong here.

Upvotes: 4

Views: 12425

Answers (1)

Charlie Clark
Charlie Clark

Reputation: 19507

Just set the number format for the cell:

sheet.cell(row=2,column=i+1).number_format = '0.00E+00'

You can also probably avoid using xrange for the loops. enumerate(sequence, start) is better when you really need to address individual cells. But, if you are simply working with sequences you can simply append them. You're code can probably be refactored to look something like the following.

Write the header

sheet.append(header)

# Write the data
for row in data:
    sheet.append([float(v) for v in row])
for cell in sheet.iter_rows(row=2):
    cell.number_format = '0.00E+00'

Upvotes: 3

Related Questions