I’m using XLWT to write excel files from .csv and I have the first column in the csv as the style for the row. How can I start writing the values beginning with the second column of each row (as to not print out the value, for example, “headerStyle”)? I’ve tried a few different ways, such as creating a col_count but haven’t had any luck.
row_count = 0
style = rowStyle
#Read each row and write to sheet
for row in csv_input:
#Iterate through each column
for col in range(len(row)):
if col == 0:
style = row[col]
else:
if(is_number(row[col]) == True):
sheet.write(row_count,col,float(row[col]),style)
else:
sheet.write(row_count,col,row[col],style)
#Increment row_count
row_count += 1
Any help is appreciated! Thanks!
I ended up figuring it out. For anyone interested, one problem was that style was coming back as a string so I created a function to fix that:
def assign_style(string):
if string=='headerStyle':
style = headerStyle
return style
Then the following would loop through while skipping the first column:
row_count = 0
#Read each row and write to sheet
for row in csv_input:
#Iterate through each column
for col in range(len(row)):
if col == 0:
style = assign_style(row[col])
elif(is_number(row[col]) == True):
sheet.write(row_count,col-1,float(row[col]),style)
else:
sheet.write(row_count,col-1,row[col],style)
#Increment row_count
row_count += 1
Use
iter(). Also, don’t iterate over therange(). Instead useenumerate(). And use the ternary operator, it helps to maintain DRY: