简体   繁体   English

Python:如何在 Excel 中仅将单元格中的第一行加粗和着色

[英]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 P1 Line 1 1号线
Line 2 2号线
Line 3 3号线
P2 P2 Line 1 1号线
Line 2 2号线
Line 3 3号线
P3 P3 Line 1 1号线
Line 2 2号线
Line 3 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.

相关问题 如何使用python在excel单元格中仅加粗字符串的一部分 - How Do I Bold only part of a string in an excel cell with python 如何用python修改现有的Excel单元格颜色 - How to modify the existing Excel cell color with python 如何使用Python从Excel文件中提取单元格格式(粗体,斜体等)? - How to extract cell format (bold, italic, …) from an Excel file using Python? Python 如何删除 word 文件的第一行和 font.bold 不起作用 - Python how to delete first line of word file and font.bold not working 如何用python xlwt库更改excel单元格的背景颜色? - How to change background color of excel cell with python xlwt library? 如何使用Python根据单元格值填充excel的背景颜色? - How to fill background color of excel base on cell value with Python? 在 Excel 文件中,如何使用 openpyxl (Python) 查找单元格的背景颜色 - In a Excel file how to find the background color of a cell using openpyxl (Python) 如何通过 Python 在 excel 单元格中仅读取没有删除线的文本? - How to read only text without strikethrough in an excel cell through Python? Python 只写第一行 - Python only writing first line 如何使用Python / XlsxWriter将单个单元格设置为数字和粗体格式 - How to set a single cell to both number and bold format with Python/XlsxWriter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM