英文:
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..)
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.
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') # 在此处,我们将内容写回到同一文件中,同时保留/更新旧内容。
输出:
英文:
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('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: # <-- change the condition(s) here
cell.fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
workbook.save('filename.xlsx') # here, we write on the same file while keeping/updating the old F.
Output :
答案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')
英文:
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('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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论