我想将变量game_type的值赋给excel单元格,但我无法这样做:
import openpyxl
wb = openpyxl.load_workbook('Table1.xlsx')
Card13 = wb.active
print Card13
class private_table():
def __init__(self, game):
if game == 13:
game_type = game
Card13['A2'] = game_type
wb.save('Table1.xlsx')
print(game_type)
elif game == '21':
game_type = int(game)
print(game_type)
elif game == '27':
game_type = int(game)
print(game_type)
else:
print("Enter correct game type")
def noc(self, cards):
if cards == 13:
game_type = Card13['A2'].value
if game_type == '13':
num_of_cards = cards
print num_of_cards
return num_of_cards
else:
print ("Please select the correct number of cards")
return("Please select the correct number of cards")
elif cards == '21':
game_type = Card13['B1'].value
if game_type == '21':
num_of_cards = cards
print num_of_cards
return num_of_cards
else:
print ("Please select the correct number of cards")
return("Please select the correct number of cards")
elif cards == '27':
game_type = Card13['B1'].value
if game_type == '27':
num_of_cards = cards
print num_of_cards
return num_of_cards
else:
print ("Please select the correct number of cards")
return("Please select the correct number of cards")
答案 0 :(得分:1)
From the documentation of openpyxl,这就是你在Excel中写的方式:
from openpyxl import Workbook
wb = Workbook()
# grab the active worksheet
ws = wb.active
# Data can be assigned directly to cells
ws['A1'] = 42
# Rows can also be appended
ws.append([1, 2, 3])
# Python types will automatically be converted
import datetime
ws['A2'] = datetime.datetime.now()
# Save the file
wb.save("sample.xlsx")
如果您决定使用xlsxwriter,这是一些工作示例,适用于Python 3.对于Python 2,请从print ()
中删除括号 - print wks2.name
。
import xlsxwriter
from xlsxwriter.utility import xl_rowcol_to_cell
wbk = xlsxwriter.Workbook('testing.xlsx')
wks = wbk.add_worksheet()
wks.write('A1', 'Hello world')
print (wks.name)
wks2 = wbk.add_worksheet()
print (wks2.name)
i = -1
for x in range(1, 1000, 11):
i+=1
cella = xl_rowcol_to_cell(i, 0) #0,0 is A1!
cellb = xl_rowcol_to_cell(i, 1)
cellc = xl_rowcol_to_cell(i, 2)
print (cella)
wks2.write(cella,x)
wks2.write(cellb,x*3)
wks2.write(cellc,x*4.5)
wbk.close()
您只需要在Python的同一目录中有一个名为testing.xlsx
的工作簿。然后你在第一张纸上得到这个:
这是在添加的表格上:
如果您使用Python运行代码,这就是您所获得的:
工作表的名称来自print(wks.name)
和print(wks2.name)
。
答案 1 :(得分:0)
以下是帮助我在Excel工作表中插入变量值的解决方案。
import openpyxl
wb = openpyxl.load_workbook('Table1.xlsx')
Card13 = wb.active
print Card13
class private_table():
def __init__(self, game):
if game == 13:
game_type = game
Card13['B1'] = game_type
wb.save('Table1.xlsx')
print(game_type)
elif game == 21:
game_type = (game)
Card13['B1'] = game_type
wb.save('Table1.xlsx')
print(game_type)
elif game == 27:
game_type = (game)
wb.save('Table1.xlsx')
Card13['B1'] = game_type
print(game_type)
else:
print("Enter correct game type")