【问题标题】:i tried to create multiple sheets in excel using python openpyxl to store different values in loop, but it creates only one sheet我尝试使用 python openpyxl 在 excel 中创建多个工作表以在循环中存储不同的值,但它只创建一个工作表
【发布时间】:2021-10-13 04:38:40
【问题描述】:

我尝试使用 python openpyxl 在 excel 中创建多个工作表以在循环中存储不同的值,但它只创建一个工作表。

from datetime import datetime
import openpyxl
from openpyxl.styles import Font

table_name = ["M-1", "M-2", "M-3"]

xltitle = datetime.now()
tit_head = "ALL_MACHINE" + xltitle.strftime("%d_%m_%Y_%H_%M_%S")+".xlsx"

for tab_nam in table_name:

    filepath = tit_head

    headings = ("NAME", "ID", "EMPLOYEE NAME",
                "NUMBER", "START TIME", "STOP TIME")

    wb = openpyxl.Workbook()
    sheet = wb.create_sheet()
    sheet.title = tab_nam

    sheet.row_dimensions[1].font = Font(bold=True)

    for colno, heading in enumerate(headings, start=1):
        sheet.cell(row=1, column=colno).value = heading

    wb.save(filepath)

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    您在循环的每次迭代中创建一个新工作簿,然后保存它,覆盖前一个工作簿。您需要移动工作簿的创建并将文件写入循环之外。你也可以移动headings的创建,这样就不需要每次都重新创建了。

    类似这样的:

    filepath = tit_head
    headings = ("NAME", "ID", "EMPLOYEE NAME",
                "NUMBER", "START TIME", "STOP TIME")
    wb = openpyxl.Workbook()
    for tab_nam in table_name:
        sheet = wb.create_sheet()
        sheet.title = tab_nam
    
        sheet.row_dimensions[1].font = Font(bold=True)
    
        for colno, heading in enumerate(headings, start=1):
            sheet.cell(row=1, column=colno).value = heading
    wb.save(filepath)
    

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多