简体   繁体   English

Openpyxl:以不同格式写入单元格

[英]Openpyxl: write cells with different format

I am writing an excel sheet. 我正在写一张Excel工作表。 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. 我想用相同的脚本写标题(带有列名)和数据(带有2个十进制数字的浮点数)。

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. 我不确定自己在做什么错在这里100%。

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. 您也可以避免将xrange用于循环。 enumerate(sequence, start) is better when you really need to address individual cells. 当您确实需要处理单个单元格时enumerate(sequence, start)会更好。 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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