我嘗試使用 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)
uj5u.com熱心網友回復:
您在回圈的每次迭代中創建一個新作業簿,然后保存它,覆寫前一個。您將需要移動作業簿創建并將檔案寫入回圈之外。您還可以移動 的創建,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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/310895.html
