如何摆脱索引列并开始在第一列中写入定义的标题

时间:2019-07-03 03:17:00

标签: python pandas xlsxwriter

excel中的输出如下:

enter image description here

所以现在我只想摆脱索引列并修改标头格式。 为此,我将使用参数:

df.to_excel(writer,'Sheet1',startrow=1, header=False,index=False)

现在:

# Write the column headers with the defined format.
for col_num, value in enumerate(df.columns.values):
    worksheet.write(0, col_num + 1, value, header_format)

但是输出看起来不正确:

那要怎么解决呢?

enter image description here

整个代码如下:

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import numpy as np

df = pd.DataFrame({'Column1':['Roman','Nick','Jarrod','Spencer','Sasha'],
                   'Column2':['Red','Blue','Green','Yellow','Orange']})


writer = ExcelWriter('TestFile.xlsx')

df.to_excel(writer,'Sheet1',startrow=1, header=False,index=False)

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
# Add a header format.
header_format = workbook.add_format({
    'bold': True,
    'text_wrap': False,
    'valign': 'top',
    'fg_color': '#D7E4BC',
    'border': 1})
# Write the column headers with the defined format.
for col_num, value in enumerate(df.columns.values):
    worksheet.write(0, col_num + 1, value, header_format)
# Close the Pandas Excel writer and output the Excel file.
writer.save()

2 个答案:

答案 0 :(得分:1)

您的列索引已关闭1。使用:

worksheet.write(0, col_num, value, header_format)

代替:

worksheet.write(0, col_num + 1, value, header_format)

答案 1 :(得分:0)

以下代码应该起作用:

import csv
df.to_excel(filename,index=False)
相关问题