编写头文件在Excel中的Excel文件

你如何循环列表中的每个元素,并把它作为excel头? 让我知道是否有重复的问题。 我目前还找不到。

row=0 col=0 j = 0 title = ['No.', 'Hue', 'Saturation', 'Value', 'Lightness', 'AComponent', 'BComponent', 'Blue Channel', 'Green Channel', 'Red Channel'] for i in title[0:len(title)]: worksheet.write(row + 1, col + j, 'title[%i]', bold) j += 1 

我想做一些像红色的文字 在这里输入图像说明

你似乎误解了两件事情:

  1. 迭代整个循环,不需要范围或索引
  2. 为了将一些外部的值replace成一个string,你不能做你正在做的事情。 Python不会对string做任何特殊的处理。

您可以使用enumeratej计数器并摆脱一个单独的计数器variables。

 for j, t in enumerate(title): worksheet.write(row + 1, col + j, t, bold) 

免责声明:我不知道如何使用xlsxwriter ,所以就书写标题的问题而言,这可能不是最好的方法。 但是,这个答案的作用是解决你的错误。

您可以使用Pandas和ExcelWriter模块

用你列表中的列创build空的DF(即你的案例中的标题)

 import pandas as pd title = ['No.', 'Hue', 'Saturation', 'Value', 'Lightness', 'AComponent', 'BComponent', 'Blue Channel', 'Green Channel', 'Red Channel'] df = pd.DataFrame(columns = title) #this create your empty data frame 

DF TO EXCEL

 from pandas import ExcelWriter writer = ExcelWriter('YourCSV.xlsx') df.to_excel(writer,'Sheet1') writer.save() #this create Excel file with your desired titles 

DF TO CSV

 df.to_csv('YourCSV.csv', sep=',')