Python: openpyxl 的列索引错误
Python: Column index error with openpyxl
我有两个要写入新 xlsx
文件的列表:
list1=[1,2,3,4]
list2=[A,B,C,D]
我希望 list1
转储到 A 列,list2
转储到 B 列:
COLUMN A COLUMN B
1 A
2 B
3 C
4 D
这是我的看法,但它引发了错误:ValueError: Invalid column index 0
。
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl.cell import get_column_letter
import os
wb = Workbook()
newdir=r'C:\Users\MyName\Desktop'
os.chdir(newdir)
dest_filename = 'Trial.xlsx'
ws=wb.active
for r in range(1,5):
for c in 'A':
ws.cell(row=r,column=0).value=list1[r]
for c in 'B':
ws.cell(row=r,column=1).value=list2[r]
wb.save(filename = dest_filename)
错误点在最后一行。有什么问题吗?
没用过openpyxl,但是看the source,好像列号必须在1到18278之间:
if not 1 <= col_idx <= 18278:
raise ValueError("Invalid column index {0}".format(col_idx))
因此,不要使用 column=0
和 column=1
,而是使用:
for r in range(1,5):
for c in 'A':
ws.cell(row=r, column=1).value = list1[r]
for c in 'B':
ws.cell(row=r, column=2).value = list2[r]
PS: for c in 'A'
和 for c in 'B'
?也许你的意思是:
for r in range(1,5):
ws.cell(row=r, column=1).value = list1[r]
ws.cell(row=r, column=2).value = list2[r]
我有两个要写入新 xlsx
文件的列表:
list1=[1,2,3,4]
list2=[A,B,C,D]
我希望 list1
转储到 A 列,list2
转储到 B 列:
COLUMN A COLUMN B
1 A
2 B
3 C
4 D
这是我的看法,但它引发了错误:ValueError: Invalid column index 0
。
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl.cell import get_column_letter
import os
wb = Workbook()
newdir=r'C:\Users\MyName\Desktop'
os.chdir(newdir)
dest_filename = 'Trial.xlsx'
ws=wb.active
for r in range(1,5):
for c in 'A':
ws.cell(row=r,column=0).value=list1[r]
for c in 'B':
ws.cell(row=r,column=1).value=list2[r]
wb.save(filename = dest_filename)
错误点在最后一行。有什么问题吗?
没用过openpyxl,但是看the source,好像列号必须在1到18278之间:
if not 1 <= col_idx <= 18278:
raise ValueError("Invalid column index {0}".format(col_idx))
因此,不要使用 column=0
和 column=1
,而是使用:
for r in range(1,5):
for c in 'A':
ws.cell(row=r, column=1).value = list1[r]
for c in 'B':
ws.cell(row=r, column=2).value = list2[r]
PS: for c in 'A'
和 for c in 'B'
?也许你的意思是:
for r in range(1,5):
ws.cell(row=r, column=1).value = list1[r]
ws.cell(row=r, column=2).value = list2[r]