如何在Python中将表格保存到Excel工作表并保留原始工作表格式?

huangapple go评论78阅读模式
英文:

How can I save a table to excel sheet with original sheet formatting in python?

问题

I have loaded the data from Excel sheet that applied cell formatting(border, merge, font..)

然后,我在Python中使用了条件语句来给特定条件下的单元格上色。我想要以这种样式再次保存表格,保持原始Excel表格的格式如下。

How can I code?
我尝试了以下代码,但没有得到想要的结果。

import pandas as pd
import numpy as np
from openpyxl import load_workbook

workbook = openpyxl.load_workbook('test.xlsx')
worksheet = workbook['Tables']

# Load the DataFrame from the Excel file
df = pd.read_excel('test.xlsx', sheet_name='Tables')

# Define the column list
column_list = df.columns.to_list()[3:]

# Define the color function
def color(df, subset=column_list, up=5, low=-5):
    tmp = df[column_list].sub(pd.to_numeric(df['Unnamed: 2'], errors='coerce'), axis=0)
    return pd.DataFrame(np.select([tmp.gt(up), tmp.lt(low)],
                                  ['background-color: #e6ffe6;',
                                   'background-color: #ffe6e6;'],
                                  None), columns=subset, index=df.index
                       ).reindex_like(df)

df.style.apply(color, axis=None).to_excel('result.xlsx', engine='openpyxl', index=False)
英文:

I have loaded the data from Excel sheet that applied cell formatting(border, merge, font..)
如何在Python中将表格保存到Excel工作表并保留原始工作表格式?

Then, I used a conditional statement in Python to colour the cells under certain conditions. I want to save the table with this style applied again, keeping the formatting of the original Excel sheet as below.

如何在Python中将表格保存到Excel工作表并保留原始工作表格式?

How can I code?
I have tried below, but I didn't get wanted.

import pandas as pd
import numpy as np
from openpyxl import load_workbook

workbook = openpyxl.load_workbook('test.xlsx')
worksheet = workbook['Tables']


# Load the DataFrame from the Excel file
df = pd.read_excel('test.xlsx', sheet_name='Tables')

# Define the column list
column_list = df.columns.to_list()[3:]

# Define the color function
def color(df, subset=column_list, up=5, low=-5):
    tmp = df[column_list].sub(pd.to_numeric(df['Unnamed: 2'], errors='coerce'), axis=0)
    return pd.DataFrame(np.select([tmp.gt(up), tmp.lt(low)],
                                  ['background-color: #e6ffe6;',
                                   'background-color: #ffe6e6;'],
                                  None), columns=subset, index=df.index
                       ).reindex_like(df)

df.style.apply(color, axis=None).to_excel('result.xlsx', engine='openpyxl', index=False)

答案1

得分: 1

代码部分不需要翻译。以下是已翻译好的部分:

在您的期望输出中,彩色单元格背后的逻辑尚不完全清楚。

无论如何,要读取/有条件地格式化/写入同一文件中的一系列单元格,请使用以下代码:

import openpyxl
from openpyxl.styles import PatternFill

workbook = openpyxl.load_workbook('filename.xlsx')

worksheet = workbook['Sheet1']

for row in worksheet.iter_rows(min_row=3, min_col=3, max_col=9):
    for cell in row:
        if cell.value == 1: # < -- 在此处更改条件
            cell.fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')

workbook.save('filename.xlsx') # 在此处,我们将内容写回到同一文件中,同时保留/更新旧内容。

输出:

如何在Python中将表格保存到Excel工作表并保留原始工作表格式?

英文:

The logic is not fully clear behind the colored cells in your expected output.

Anyway, to read/conditionnaly-format/write a range of cells (on the same file), use this :

import openpyxl
from openpyxl.styles import PatternFill

workbook = openpyxl.load_workbook(&#39;filename.xlsx&#39;)

worksheet = workbook[&#39;Sheet1&#39;]

for row in worksheet.iter_rows(min_row=3, min_col=3, max_col=9):
    for cell in row:
        if cell.value == 1: # &lt;-- change the condition(s) here
            cell.fill = PatternFill(start_color=&#39;FFFF00&#39;, end_color=&#39;FFFF00&#39;, fill_type=&#39;solid&#39;)

workbook.save(&#39;filename.xlsx&#39;) # here, we write on the same file while keeping/updating the old F.

Output :

如何在Python中将表格保存到Excel工作表并保留原始工作表格式?

答案2

得分: -1

I used the below given code and it kept the formatting and also changed the cell color on condition.
Using pandas 1.5.2 (I don't think it has something to do with it) and openpyxl 3.0.9. It keeps the merge, border, font style, weight, family, and color as it was in the test file.

import openpyxl
from openpyxl.styles import PatternFill

workbook = openpyxl.load_workbook('test.xlsx')

worksheet = workbook['Sheet1']
for row in worksheet.iter_rows(min_row=2, min_col=1, max_col=3):
   if row[0].value > 1:
      row[2].fill = PatternFill(start_color="FDFF00", end_color="FDFF00", fill_type='solid')

workbook.save('newfilename.xlsx')

如何在Python中将表格保存到Excel工作表并保留原始工作表格式?

如何在Python中将表格保存到Excel工作表并保留原始工作表格式?

如何在Python中将表格保存到Excel工作表并保留原始工作表格式?

英文:

I used the below given code and it kept the formatting and also changed the cell color on condition.
Using pandas 1.5.2 (i dont think it has something to do with it)
and openpyxl 3.0.9. It keep the meger, border, font style, weight, family and color as it was in test file.

import openpyxl
from openpyxl.styles import PatternFill

workbook = openpyxl.load_workbook(&#39;test.xlsx&#39;)

worksheet = workbook[&#39;Sheet1&#39;]
for row in worksheet.iter_rows(min_row=2, min_col=1, max_col=3):
   if row[0].value &gt; 1:
      row[2].fill = PatternFill(start_color=&quot;FDFF00&quot;, end_color=&quot;FDFF00&quot;, fill_type=&#39;solid&#39;)

workbook.save(&#39;newfilename.xlsx&#39;)

如何在Python中将表格保存到Excel工作表并保留原始工作表格式?

如何在Python中将表格保存到Excel工作表并保留原始工作表格式?

如何在Python中将表格保存到Excel工作表并保留原始工作表格式?

huangapple
  • 本文由 发表于 2023年4月13日 17:53:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004064.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定