簡體   English   中英

如何使用openpyxl和python3為excel工作表中的一系列單元格(列和行)提供字體顏色?

[英]How to give font color to a range of cells (columns and rows) in excel worksheet using openpyxl and python3?

我想在 Excel 工作表openpyxl紅色設置為一系列單元格(一列到另一列)並使用openpyxl

我能夠從官方文檔中找到如何為單元格賦予某種顏色,但我無法弄清楚如何給出范圍。

基本上,我想要這樣的東西使用 openpyxl:

inheritance_cell_format = wb.add_format()
inheritance_cell_format.set_font_color('red')
ws.conditional_format( 0, skip_cols-2, ws.max_row, skip_cols-1, { 'type': 'cell', 'criteria': '=', 'value': '⇒', 'format': inheritance_cell_format } )

上面的代碼片段適用於 xlsxwriter。

到目前為止,顯然,我在第一行收到一個錯誤,指出工作簿沒有屬性“ add_format()

您可以使用 .iter_rows() 或 iter_cols() 方法為帶有循環的范圍着色。 您可以導入 PatternFill 為其着色。

import openpyxl as px
from openpyxl.styles import PatternFill

wb = px.load_workbook(file) #imports file
ws = wb.active #Active sheet (first one)
for row in sheet.iter_rows(min_row=1, max_col=3, max_row=2): #max row and col (range)
   for cell in row:
       cell.fill = PatternFill(start_color="FF0000", fill_type = "solid") #html colors


wb.save(file)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM