2017-08-06 47 views
1

當條件滿足時,需要對背景單元格着色。Python如何優化繪製背景單元格

import xlrd 
import xlsxwriter 

workbook = xlsxwriter.Workbook('file2.xlsx') 
worksheet = workbook.add_worksheet() 
format = workbook.add_format() 
format.set_font_color('red') 

excel_data_file1 = xlrd.open_workbook('file1.xlsx') 
sheet_file1 = excel_data_file1.sheet_by_index(0) 

excel_data_file2 = xlrd.open_workbook('file2.xlsx') 
sheet_file2 = excel_data_file2.sheet_by_index(0) 

col1 = sheet_file1.col(colx=0) 
col2 = sheet_file2.col(colx=0) 

a=set() 
for i in range(len(col1)): 
    a.add(sheet_file1.cell_value(rowx=i, colx=0)) 

for j in range(len(col2)): 
    cellVal2 = sheet_file2.cell_value(rowx=j, colx=0) 

    if cellVal2 not in a: 
     worksheet.write_blank(j, 0, format) 

worksheet.write_blank(j, 0, format) 

不行的,表中的所有值都被清除

回答

1

這是一個小演示,它使用Pandas module

讓我們先來生成兩個示例Excel文件:

import pandas as pd 

pd.DataFrame(np.random.randint(10, size=(5, 3)), columns=list('abc')) \ 
    .to_excel('d:/temp/f1.xlsx', index=False)  
pd.DataFrame(np.random.randint(10, size=(5, 3)), columns=list('abc')) \ 
    .to_excel('d:/temp/f2.xlsx', index=False) 

現在,我們將讀/把它解析爲Pandas.DataFrame的:

In [89]: df1 = pd.read_excel(r'D:\temp\f1.xlsx') 

In [90]: df2 = pd.read_excel(r'D:\temp\f2.xlsx') 

In [91]: df1 
Out[91]: 
    a b c 
0 0 5 3 
1 9 4 9 
2 3 6 5 
3 9 1 5 
4 2 5 0 

In [92]: df2 
Out[92]: 
    a b c 
0 0 7 9 
1 2 2 3 
2 4 9 0 
3 7 9 1 
4 8 6 5 

一個輔助功能,突出了細胞在一個系列缺少在其他系列中:

def highlight_missing(s1, s2, col_name): 
    if s1.name == col_name: 
     return ['' if x in s2.values else 'background-color: yellow' for x in s1] 
    return [''] * len(s1) 

最後我們可以用h創建一個新的Excel文件ighlighted缺失值:

df1.style.apply(highlight_missing, s2=df2['a'], col_name='a') \ 
    .to_excel('d:/temp/new.xlsx', index=False, engine='openpyxl') 

結果:

enter image description here