GeoffW
GeoffW

Reputation: 1

write comma delimited text to excel

I'm iterating through a bunch of SDE's, then iterating through those and producing feature class titles, and it's in a list. I then perform a list.replace() and turn it into a comma delimited string.

So, I want to take that delimited string such as:
SDE_name1,thing1,thing2,thing3,thing4
SDE_name2,thing1,thing2,thing3,thing4
SDE_name3,thing1,thing2,thing3,thing4

and insert it into excel using XLWT

I can get it to write the entire length into one cell, with or without the commas, but I'd like it to write each item into a new column...

So column A would have SDE_name1
Column B would have thing1
columb C would have thing2 etc etc etc

So far I've tried:

listrow=2
listcol=0
for row in list:
    worksheet.write(listrow,listcol,row,style)
    listrow+=1
wbk.save(bookname)

and

listrow=2
listcol=0
list=something.split(anotherlist,delimiter=",")
for row in list:
    worksheet.write(listrow,listcol,row,style)
    listrow+=1
wbk.save(bookname)

So both with and without a delimiter. Either way, both write everything to one column left to right. It will write each item in the list to a new row...but I need it to write each item after the comma to a new column.

Any idea?

Upvotes: 0

Views: 2602

Answers (1)

Mark Streatfield
Mark Streatfield

Reputation: 3209

You are not iterating through the columns. As it's not clear exactly what the variables in your example refer to, assume you start with the following

data = ["SDE_name1,thing1,thing2,thing3,thing4", 
        "SDE_name2,thing1,thing2,thing3,thing4",
        "SDE_name3,thing1,thing2,thing3,thing4"]

The code to write the Excel file becomes:

rowCount = 2
for row in data:                  # row = "SDE_name1,thing1,thing2,thing3,thing4"
    colCount = 0
    for column in row.split(","): # column = ["SDE_name1", "thing1", "thing2", "thing3", "thing4"]
        worksheet.write(rowCount, colCount, column, style)
        colCount += 1
    rowCount += 1
wbk.save(bookname)

Upvotes: 1

Related Questions