Write headers to excel file in python

拥有回忆 提交于 2019-12-08 06:09:14

问题


How do you loop through each element in a list and put it as excel header? Let me know if there is a duplicate question. I couldnt find it so far.

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

I wanted to do something like the text in red


回答1:


You seem to have misunderstood two things:

  1. To iterate over the whole loop, no ranges or indices are needed
  2. To substitute some external value into a string, you cannot do what you are doing. Python does not do anything special with the string.

You can use enumerate for the j counter and get rid of a separate counter variable.

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

Disclaimer: I do not know how to work with xlsxwriter, so as far as the question of writing headers is concerned, this may not be the best way. However, what this answer does is address your errors.




回答2:


You can use Pandas and ExcelWriter module

Create empty DF with columns from your list (i.e. title in your case)

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=',')


来源:https://stackoverflow.com/questions/46114993/write-headers-to-excel-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!