pandas导出到excel没有格式

时间:2018-04-20 08:10:26

标签: python excel pandas pandas.excelwriter

我想将数据从dataframe导出到excel,它已经是格式布局(颜色,单元格等)

此代码覆盖所有工作表,而不是我想要导出数据而不更改excel布局。

可能吗?

使用XlsxWriter作为引擎创建Pandas Excel编写器。

writer = pd.ExcelWriter('C:/pandas_positioning.xlsx', engine='xlsxwriter')


df.to_excel(writer, sheet_name='my_data',
         startrow=7, startcol=4, header=False, index=False)

关闭Pandas Excel编写器并输出Excel文件。

writer.save()

1 个答案:

答案 0 :(得分:0)

手动执行。

示例:

WB = 'C:/pandas_positioning.xlsx'
WS = 'my_data'

writer = pd.ExcelWriter(WB, engine='openpyxl')

wb = openpyxl.load_workbook(WB)
wb.create_sheet(WS)
writer.book = wb
writer.sheets = {x.title: x for x in wb.worksheets}

ws = writer.sheets[WS]

for icol, col_name in zip(range(len(df.columns)+1), df.columns):
    ws.cell(1, icol+2, col_name)

for irow, row_name in zip(range(len(df.columns)+1), df.index):
    ws.cell(irow+2, 1, row_name)

for (_, row), icol in zip(df.iterrows(), range(len(df.index) + 1)):
    for (_, cell), c in zip(row.iteritems(), range(len(df.columns) + 1)):
        ws.cell(icol+2, c+2).value = cell

writer.save()