如何摆脱索引列并开始在第一列中写入已定义的 header
How to get rid of index columns and start writing defined header in first column
excel 中的输出如下所示:
所以现在我只想去掉索引列并修改 header 格式。
为此,我将使用参数:
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)
但输出看起来不正确:
那么有什么办法可以解决呢?
完整代码如下:
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()
以下代码应该有效:
import csv
df.to_excel(filename,index=False)
您的列索引偏移 1。使用:
worksheet.write(0, col_num, value, header_format)
而不是:
worksheet.write(0, col_num + 1, value, header_format)
excel 中的输出如下所示:
所以现在我只想去掉索引列并修改 header 格式。 为此,我将使用参数:
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)
但输出看起来不正确:
那么有什么办法可以解决呢?
完整代码如下:
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()
以下代码应该有效:
import csv
df.to_excel(filename,index=False)
您的列索引偏移 1。使用:
worksheet.write(0, col_num, value, header_format)
而不是:
worksheet.write(0, col_num + 1, value, header_format)