0

I want to import the python list to excel. My example code is:

import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = 1
wb = excel.Workbooks.Add()
ws = wb.Worksheets("Sheet1")

list1 =("a","b","c","c","c","c","c","c","c","c")

ws.Range("B1:B10").Value = list1

How I have to change the list1 type to use the code ws.Range("B1:B10").Value = list1? What kind of list can use in excel file?

pnuts
  • 58,317
  • 11
  • 87
  • 139
Tran Binh
  • 1
  • 1
  • List1 is a tuple, you should use square brackets for a list: `list1 =["a", "b" ... "c"]`. Not sure if this matters. You could loop or use the `xlwt` library to solve this. – Ed Smith Apr 15 '15 at 07:12
  • thanks @EdSmith, actually I want my list become like that `list1 =(("a",),("b",),("c",),("c",),("c",),("c",).....)` It will be easy to write to excel. And I do not want to use other library except win32. That is the problem! – Tran Binh Apr 15 '15 at 07:59

1 Answers1

0

It looks like this post may do what you need by wrapping your range statement in a function like:

def writeLinesToExcel(ws,lines): 
    ws.Range("A1:"+chr(len(lines)+96).upper()+str(len(lines[0]))).Value=lines

Then you can call writeLineToExcel(ws,list1). You can also use things like [["a"],["b"]] apparently... Based on your question, I'm not sure this appears to be working for you. If your data is simple enough, you could just use a loop,

def writeRowsToExcel(ws,col,rows): 

    for i,l in enumerate(rows):
        ws.Cells(col,i)= l

then call writeRowsToExcel(ws, col, rows). Other posts suggest this will be slow and to use other libraries like xlwt.

Community
  • 1
  • 1
Ed Smith
  • 12,716
  • 2
  • 43
  • 55
  • thanks @Ed Smith, Actually, I do not want to create a loop to write data to excel file because it will be slow if my data is big. So I try another method, I will create a tuple for mys list first and then write to excel file `for i in list:` `new_list.append((i,))` `ws.Range(B1,B10) = new_list ` Do you think is it ok? – Tran Binh Apr 16 '15 at 00:54
  • I don't have a windows machine to test, it looks like the syntax you use should work based on other posts -- do you have the latest version of win32com? Sorry, realised the link above us wrong, I've updated. – Ed Smith Apr 16 '15 at 10:20
  • I download it from the link [win32com link](http://sourceforge.net/projects/pywin32/files/pywin32/) – Tran Binh Apr 17 '15 at 01:30