我已经安装了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,))
答案 0 :(得分:0)
您使用的是= +而不是+ =。下面的代码应该工作。我还将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,))