Python 使用Styleframe从Excel中提取单个单元格的样式

Python 使用Styleframe从Excel中提取单个单元格的样式,python,pandas,styleframe,Python,Pandas,Styleframe,我正在尝试编写一个脚本,将两个excel文件合并在一起。一个是手工处理的,并对其进行了大量自定义格式设置,另一个是自动生成的文件。在pandas中进行合并非常简单,但是保存格式却很麻烦。我找到了styleframe库,它似乎可以简化我的工作,因为它可以在原始数据之外导入样式信息。然而,我在实际实现代码时遇到了问题 我的问题是:如何从excel中的每个单元格中提取样式信息,然后将其应用于合并的数据框?请注意,数据在列或行之间的格式不一致,因此我认为不能以这种方式应用样式。以下是我代码的相关部分:

我正在尝试编写一个脚本,将两个excel文件合并在一起。一个是手工处理的,并对其进行了大量自定义格式设置,另一个是自动生成的文件。在pandas中进行合并非常简单,但是保存格式却很麻烦。我找到了styleframe库,它似乎可以简化我的工作,因为它可以在原始数据之外导入样式信息。然而,我在实际实现代码时遇到了问题

我的问题是:如何从excel中的每个单元格中提取样式信息,然后将其应用于合并的数据框?请注意,数据在列或行之间的格式不一致,因此我认为不能以这种方式应用样式。以下是我代码的相关部分:

#iterate thorough all cells of merged dataframe
for rownum, row in output_df.iterrows():
    for  column, value in row.iteritems(): 
        filename = row['File Name']

        cur_style = orig_excel.loc[orig_excel['File Name'] == filename, column][0].style #pulls the style of relevant cell in the original excel document
        target_style = output_df.loc[output_df['File Name'] == filename, column][0].style #style of the cell in the merged dataframe
        target_style = cur_style #set style in current output_df cell to match original excel file style
这段代码运行(缓慢),但似乎并没有对输出样式框应用任何样式


通过查看文档,我并没有真正看到在单个styleframe容器级别应用样式的方法——所有操作都是以行或列的形式进行的。您似乎还需要使用styler对象来设置样式。

解决了这个问题。我重新调整了数据帧,这样我就可以只使用
.at
而不是
.loc
查找。这一点,再加上
apply\u style\u by\u index
方法,让我达到了我需要的位置:

for index, row in orig_excel.iterrows():
    for  column, value in row.iteritems(): 
        index_num = output_df.index.get_loc(index)

        #Pull style to copy to new df
        cur_style = orig_excel.at[index, column].style 
      
        #Apply original style to new df
        output_df.apply_style_by_indexes(output_df.index[index_num], 
                                         cur_style, 
                                         cols_to_style = column)

有帮助吗?是的,有帮助,尽管它只处理了问题的一半——有没有办法通过读取给定单元格的.style来生成样式器对象?或者我必须根据.style所说的内容手动设置styler对象中的所有参数吗?如果您使用的是
StyleFrame.read\u excel(…,read\u style=True)
,那么每个
.style
属性都已经是
styler
对象,因为
bg\u color
确实是一个字符串,从你的第二个例子中删除它我让代码工作了。感谢您的帮助,特别是感谢您创建了Styleframe库!