[英]Python Excel writing values from csv starting at 2nd column
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. 我正在使用XLWT从.csv写入excel文件,并且我将csv中的第一列作为该行的样式。 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")?
如何开始从每行第二列开始写入值(以免打印出该值,例如“ headerStyle”)? I've tried a few different ways, such as creating a col_count but haven't had any luck.
我尝试了几种不同的方法,例如创建了一个col_count,但没有任何运气。
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()
. 使用
iter()
。 Also, don't iterate over the range()
. 另外,不要迭代
range()
。 Instead use enumerate()
. 而是使用
enumerate()
。 And use the ternary operator, it helps to maintain DRY: 并使用三元运算符,它有助于维护DRY:
for row_count, row in enumerate(csv_input):
columns = iter(row)
style = next(columns)
for col_count, col in enumerate(columns, start=1):
sheet.write(
row_count,
col_count,
float(col) if is_number(col) else col,
style
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.