[英]Python: How to Bold and Color only the First Line in cell in Excel
There is a table shows as following, each cell of "Description" column contains multiple lines of description about the product.有一个表格显示如下,“描述”列的每个单元格包含多行关于产品的描述。 I want to change the first line in each cell font to bold and color in red, and then export the worksheet to a new file.
我想将每个单元格字体中的第一行更改为粗体并以红色显示,然后将工作表导出到新文件。
Product![]() |
Description![]() |
---|---|
P1 ![]() |
Line 1 ![]() Line 2 ![]() Line 3 ![]() |
P2 ![]() |
Line 1 ![]() Line 2 ![]() Line 3 ![]() |
P3 ![]() |
Line 1 ![]() Line 2 ![]() Line 3 ![]() |
import pandas as pd
df = pd.read_excel(fileLocation)
df.style.set_properties(subset=['Description'], **{'font-weight': 'bold', 'color': 'red'}).to_excel('newFile.xlsx', engine='openpyxl')
I am using Python and Pandas moudle.我正在使用 Python 和 Pandas 模块。 Above code segment bold and color all the lines in cell.
上面的代码段加粗并为单元格中的所有行着色。 Is there a way to only bold and color the first line in cell?
有没有办法只将单元格中的第一行加粗和着色? Or is there any other moudle can help with?
或者有没有其他的模块可以提供帮助?
Use:利用:
df['Description'] = df['Description'].str.split('\n')
df1 = df.explode('Description')
df1['r'] = range(len(df1))
df1 = df1.set_index(['Product', 'r'])
def coloring(x):
c1 = 'color: red'
c = ''
mask1 = x['Description'] == 'Line 1'
df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
df1.loc[mask1, 'Description'] = c1
return df1
df1 = df1.style.apply(coloring, axis=None)
Output: Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.