-1

I have two lists which I want to write to a new xlsx file:

list1=[1,2,3,4]
list2=[A,B,C,D]

I want list1 to be dumped to column A and list2 to column B:

COLUMN A     COLUMN B
1            A
2            B
3            C
4            D

This is my take on it, but it raises the error: 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)

The error points at the last line. What is wrong with it?

Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69
FaCoffee
  • 7,609
  • 28
  • 99
  • 174
  • 2
    1-indexing is covered in the documentation. – Charlie Clark Jan 12 '16 at 19:21
  • Why did I get the down vote? I wish we were forced to give explanations without arbitrarily down voting anyone – FaCoffee Jan 12 '16 at 19:22
  • 1
    I added a comment after downvoting. You obviously didn't spend much time reading the docs. But, seriously, who cares that much about being downvoted? – Charlie Clark Jan 13 '16 at 08:21
  • 1
    You might be right. But being this some kind of peer-reviewed system, negative comments can be as constructive as positive ones, so I would appreciate if someone said "look, this is what is wrong with your question...". I could very well surf the depository and downvote all of the questions arbitrarily - what kind of contribution would that be, without giving any explanation? I would suggest this amendment to the moderators - when downvoting, an explanation is compulsory. – FaCoffee Jan 13 '16 at 09:02

1 Answers1

7

Never used openpyxl, but by looking at the source, it seems that column numbers must be between 1 and 18278:

if not 1 <= col_idx <= 18278:
    raise ValueError("Invalid column index {0}".format(col_idx))

Therefore, instead of using column=0 and column=1, use:

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' and for c in 'B'? Perhaps you meant:

for r in range(1,5):
    ws.cell(row=r, column=1).value = list1[r]
    ws.cell(row=r, column=2).value = list2[r]
Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69