将 headers 写入 python 中的 excel 文件
Write headers to excel file in python
如何遍历列表中的每个元素并将其作为 excel header?让我知道是否有重复的问题。至今没找到。
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
我想做一些像红色文字一样的事情
你好像误解了两点:
- 要遍历整个循环,不需要范围或索引
- 要将一些外部值替换为字符串,你不能做你正在做的事情。 Python 不对字符串做任何特殊处理。
您可以将 enumerate
用于 j
计数器并删除单独的计数器变量。
for j, t in enumerate(title):
worksheet.write(row + 1, col + j, t, bold)
免责声明:我不知道如何使用xlsxwriter
,所以就写headers的问题而言,这可能不是是最好的方法。但是,此答案的作用是解决您的错误。
您可以使用 Pandas 和 ExcelWriter 模块
使用列表中的列(即您的标题)创建空 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 到 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 转 CSV
df.to_csv('YourCSV.csv', sep=',')
如何遍历列表中的每个元素并将其作为 excel header?让我知道是否有重复的问题。至今没找到。
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
我想做一些像红色文字一样的事情
你好像误解了两点:
- 要遍历整个循环,不需要范围或索引
- 要将一些外部值替换为字符串,你不能做你正在做的事情。 Python 不对字符串做任何特殊处理。
您可以将 enumerate
用于 j
计数器并删除单独的计数器变量。
for j, t in enumerate(title):
worksheet.write(row + 1, col + j, t, bold)
免责声明:我不知道如何使用xlsxwriter
,所以就写headers的问题而言,这可能不是是最好的方法。但是,此答案的作用是解决您的错误。
您可以使用 Pandas 和 ExcelWriter 模块
使用列表中的列(即您的标题)创建空 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 到 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 转 CSV
df.to_csv('YourCSV.csv', sep=',')