1

我正在使用 XLWT 从 .csv 编写 excel 文件,并且我将 csv 中的第一列作为该行的样式。如何从每行的第二列开始写入值(以不打印出值,例如“headerStyle”)?我尝试了几种不同的方法,例如创建 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

任何帮助表示赞赏!谢谢!

我最终弄清楚了。对于任何感兴趣的人,一个问题是样式作为字符串返回,所以我创建了一个函数来解决这个问题:

def assign_style(string):
    if string=='headerStyle':
        style = headerStyle
        return style

然后以下内容将在跳过第一列时循环:

    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
4

1 回答 1

0

使用iter(). 另外,不要遍历range(). 而是使用enumerate(). 并且使用三元运算符,有助于保持 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
        )
于 2012-02-24T14:24:06.123 回答