使用python在excel条件下绘制单元格

时间:2018-07-31 13:35:59

标签: python excel

我正在创建一个Excel报告,该报告应该给我自动测试的结果。应该说他们是否失败/通过了。 我使用以下代码从csv创建了excel报告:

 import pandas as pd
    import string
    writer = pd.ExcelWriter("file.xlsx", engine="xlsxwriter")


    df = pd.read_csv("K:\\results.csv")
    df.to_excel(writer, sheet_name=os.path.basename("K:\\results.csv"))


    # skip 2 rows
    df.to_excel(writer, sheet_name='Sheet1', startrow=2, header=False, index=False)

    workbook = writer.book
    worksheet = writer.sheets['Sheet1']
    # Add a header format.
    header_format = workbook.add_format({
        'bold': True,
        'fg_color': '#ffcccc',
        'border': 1})

    # create dictionary for map length of columns
    d = dict(zip(range(25), string.ascii_uppercase))
    print (d)

    max_len = d[len(df.columns) - 1]
    print(max_len)
    # C
    # dynamically set merged columns in first row
    worksheet.merge_range('A1:' + max_len + '1', 'This Sheet is for Personal Details')

    for col_num, value in enumerate(df.columns.values):
        # write to second row
        worksheet.write(1, col_num, value, header_format)

        column_len = df[value].astype(str).str.len().max()
        column_len = max(column_len, len(value)) + 3
        worksheet.set_column(col_num, col_num, column_len)




    writer.save()

现在,如果我有一个单元格中带有“成功”一词,我想将其颜色变为绿色,如果我在excel中有一个单元格中显示“失败”,我想将其颜色变为红色。如何在excel文件中写入内容的条件下访问特定单元格? 谢谢。

1 个答案:

答案 0 :(得分:2)

您可以为此使用条件格式:

import pandas as pd


# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': ['success', 'bar', 'fail', 'foo', 'success']})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add a format for fail. Light red fill with dark red text.
fail_format = workbook.add_format({'bg_color': '#FFC7CE',
                                   'font_color': '#9C0006'})

# Add a format for pass. Green fill with dark green text.
pass_format = workbook.add_format({'bg_color': '#C6EFCE',
                                   'font_color': '#006100'})

# Apply conditional formats to the cell range.
worksheet.conditional_format('B2:B6', {'type':     'text',
                                       'criteria': 'containing',
                                       'value':    'fail',
                                       'format':   fail_format})

worksheet.conditional_format('B2:B6', {'type':     'text',
                                       'criteria': 'containing',
                                       'value':    'success',
                                       'format':   pass_format})

# Close the Pandas Excel writer and output the Excel file.
writer.save()

输出:

enter image description here

请参阅Working with Conditional Formatting上的XlsxWriter文档。请注意,您也可以使用数字(行,列)范围而不是A1:D4范围,请参阅conditional_format()