Reputation: 31
I am trying to write lists into excel, the list contains a couple of columns.
I have included my code below. It seems to only extract the first value. I am fairly new to python, what am I missing?
Code:
import win32com.client as win32
#
Z = [3,4,6,8,9,11,40]
Q = ['x','y','z','e','g','AA','BB']
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Add()
ws = wb.Worksheets.Add()
ws.Name = "MyNewSheet"
ws.Range(ws.Cells(1,1),ws.Cells(1,2)).Value = ['Z','Q']
for i,e in enumerate (Z):
ws.Range("A2:A8").Value = [ i for i in (Z)]
for i,e in enumerate (Z):
ws.Range("B2:B8").Value = [ i for i in (Q)]
wb.SaveAs('beta.xlsx')
excel.Application.Quit()
Upvotes: 1
Views: 2293
Reputation: 49812
It appears that it wants to write the values as rows. So, this re-aligns the writes to be by row:
Code:
import win32com.client as win32
Z = [3, 4, 6, 8, 9, 11, 40]
Q = ['x', 'y', 'z', 'e', 'g', 'AA', 'BB']
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Add()
ws = wb.Worksheets.Add()
ws.Name = "MyNewSheet"
ws.Range("A1:B1").Value = ['Z', 'Q']
ws.Range("A2:B8").Value = list(zip(Z, Q))
wb.SaveAs('beta.xlsx')
excel.Application.Quit()
Results:
Z Q
3 x
4 y
6 z
8 e
9 g
11 AA
40 BB
Upvotes: 2