简体   繁体   中英

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.

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'

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