gpt4 book ai didi

excel - xlwings 与 pandas 本地导出与多索引数据帧 : how to reconcile?

转载 作者:行者123 更新时间:2023-12-02 04:03:38 26 4
gpt4 key购买 nike

我将从一张图片开始,因为它清楚地解释了使用 pandas native 导出和 xlwings 导出多重索引的问题

enter image description here

本质上,我希望使用 Xlwings 完成“Pandas 原生”结果[正确导出到 Excel 的多重索引],因为我还有很多其他功能XlWings 可以做到,而其他人则不能(即使使用 ExcelWriter 之类的也不行,因为我必须清除工作表,并且我在同一张工作表中插入了一个非 python 的东西,这会初始化时也会被清除)

使用的代码:

import pandas as pd
import numpy as np
import xlwings as xw
import os

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]

tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = pd.DataFrame(np.random.randn(8, 8), index=index).transpose()
print(s)

# EXPORT

filename = 'format_excel_export.xlsx'
s.to_excel(filename)

outpath = os.path.join(os.path.abspath(os.path.dirname(__file__)), filename)
os.path.sep = r'/'
wb = xw.Workbook(outpath)

xw.Range('Sheet1', 'A13').value = s

最佳答案

您可以实现一个自定义转换器,以 Pandas 的方式对其进行格式化,请参阅 here .

但是,从 v0.7.2 开始,xlwings 本身尚不支持粗体字体、合并单元格和单元格边框。您可以通过回退到 pywin32(在 Windows 上)来解决此问题,请参阅 here .

本质上,您的自定义转换器需要重写 write_value 方法,请参阅 here .

在某个时候将其构建到库中确实有意义,因此我提出了一个问题,请参阅 here .

关于excel - xlwings 与 pandas 本地导出与多索引数据帧 : how to reconcile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38305346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com