SoFunction
Updated on 2024-10-29

python implementation xlwt xlrd add color to excel rows by specifying conditions

First read the excel file with xlrd - "book object a

Getting the specified sheet page xlrd object

Copy a to get b with the copy method of xlutils copy

Modify b by determining the column value of a

Save b Get result

Previously also tried directly with xlwt to manipulate the sheetwork object to achieve the operation of adding color to the specified line, due to limited capacity, and ultimately did not find a suitable method, and ultimately changed the method First read out, because the workbook object can get the number of rows and columns of the operation, filtering the keyword is more convenient, so the above code is a demo, but this approach There are still drawbacks, I export the dataframe to excel, there is no suitable method to add color to the specified columns, can only be temporarily dropped to the local, and then read out, it is very troublesome, I do not know if there is a sheetwork directly to the method of workbook, but also have to learn ah ~!

Additional knowledge:python How to colorize cells with certain values in a column in excel

Effect:

The code is as follows:

import xlwt
import xlrd
from  import copy
#create execl
def create_execl(file_name):
 wb = ()
 ws = wb.add_sheet('Info')
 (0, 0, "1")
 (1, 0, "2")
 (2, 0, "3")
 (3, 0, "2")
 (file_name)
#cell coloring
def color_execl(file_name):
 styleBlueBkg = ('pattern: pattern solid, fore_colour red;') # Red
 rb = xlrd.open_workbook(file_name)  # Open the file
 ro = ()[0]      #Read form 0
 wb = copy(rb)       # Utilize the copy function under copy
 ws = wb.get_sheet(0)     # Get form 0
 col = 0         # Specify the columns to be modified
 for i in range():    # Loop through all the rows
  result = int((i, col).value)
  if result == 2:      #Determine if it's equal to 2
   (i,col,(i, col).value,styleBlueBkg)
 (file_name)
 
if __name__ == '__main__':
 file_name = ''
 create_execl(file_name)
 color_execl(file_name)

The above this python implementation xlwt xlrd specifying conditions to add color to excel rows is all I have shared with you.