[英]Python program that writing in an excel file is writing last line only
我已經安裝了openpyxl模塊,現在我正在嘗試將一些數據寫入excel文件,以這種方式在一張表中填充excel文件:
["01/01/2016", "05:00:00", 3]
進入第1行,列A,B,C
["01/02/2016", "06:00:00", 4]
進入第2行,列A,B,C
["01/03/2016", "07:00:00", 5]
進入第3行,列A,B,C
["01/04/2016", "08:00:00", 6]
進入第4行,列A,B,C
["01/05/2016", "09:00:00", 7]
進入第5行,列A,B,C
當我嘗試運行代碼時,獲得以下結果:
碼:
import os, sys
from openpyxl import Workbook
from datetime import datetime
dt = datetime.now()
list_values = [["01/01/2016", "05:00:00", 3],
["01/02/2016", "06:00:00", 4],
["01/03/2016", "07:00:00", 5],
["01/04/2016", "08:00:00", 6],
["01/05/2016", "09:00:00", 7]]
wb = Workbook()
sheet = wb.active
sheet.title = "Data"
row = 1
sheet['A' + str(row)] = "Date"
sheet['B' + str(row)] = "Hour"
sheet['C' + str(row)] = "Value"
for item in list_values:
sheet['A' + str(row)] = item[0]
sheet['B' + str(row)] = item[1]
sheet['C' + str(row)] = item[2]
row =+ 1
filename = 'Book_3.xlsx'
os.chdir(sys.path[0])
os.system('start excel.exe "%s\\%s"' %(sys.path[0], filename,))
您使用的是= +而不是+ =。 下面的代碼應該工作。 我還將sys.path [0]更改為os.getcwd(),該文件將寫入當前工作目錄。 還添加了wb.save,因為其他代碼沒有產生輸出。
import os, sys
from openpyxl import Workbook
from datetime import datetime
dt = datetime.now()
list_values = [["01/01/2016", "05:00:00", 3],
["01/02/2016", "06:00:00", 4],
["01/03/2016", "07:00:00", 5],
["01/04/2016", "08:00:00", 6],
["01/05/2016", "09:00:00", 7]]
wb = Workbook()
sheet = wb.active
sheet.title = "Data"
row = 1
sheet['A' + str(row)] = "Date"
sheet['B' + str(row)] = "Hour"
sheet['C' + str(row)] = "Value"
for item in list_values:
sheet['A' + str(row)] = item[0]
sheet['B' + str(row)] = item[1]
sheet['C' + str(row)] = item[2]
row += 1
dest_filename = 'Book_3.xlsx'
wb.save(filename = dest_filename)
os.chdir(os.getcwd())
os.system('start excel.exe "%s\\%s"' %(os.getcwd(), filename,))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.