Applying formatting row by row in addition to column formatting with xlsxwriter

后端 未结 1 1723
醉话见心
醉话见心 2021-01-02 21:10

I am formatting all of my columns in an excel file using the xlsxwriter module:

def to_excel(video_report, feed):
    # Create a Pandas Excel writer using Xl         


        
相关标签:
1条回答
  • 2021-01-02 21:49

    Modifying the XLSXWriter sample code at URL http://xlsxwriter.readthedocs.org/en/latest/example_conditional_format.html

    I suggest formatting as you iterate over the data, using the row value in a test. For example...

    While writing data:

    ###############################################################################
    #
    # Example 9.
    #
    caption = ('Rows with odd numbers are in light red. '
               'Rows with even numbers are in light green.')
    
    # Write the data.
    worksheet9.write('A1', caption)
    
    for row, row_data in enumerate(data):
        if row%2 == 0:
            worksheet9.write_row(row + 2, 1, row_data, format1)
        else:
            worksheet9.write_row(row + 2, 1, row_data, format2)
    

    After writing data:

    ###############################################################################
    #
    # Example 10.
    #
    #
    caption = ('Rows with odd numbers are in light red. '
               'Rows with even numbers are in light green.')
    #
    # Write the data.
    worksheet10.write('A1', caption)
    ##
    for row, row_data in enumerate(data):
        worksheet10.write_row(row + 2, 1, row_data)
    ##
    # Write a conditional format over a range.
    for row, row_data in enumerate(data):
        if row%2 == 0:
            worksheet10.set_row(row + 2, None, format1)
        else:
            worksheet10.set_row(row + 2, None, format2)
    

    Per https://support.office.com/en-in/article/Apply-shading-to-alternate-rows-in-a-worksheet-a443b0f5-2025-42f6-9099-5de09c05e880 , Microsoft offers two methods to achieve alternating row formats : Conditional Formatting OR Table Style "Banded Rows".

    Conditional Formatting with formula =MOD(ROW(),2)=0 completes, but Excel 2013 cannot interpret it.

    # Write a conditional format over a range DOES NOT WORK
    worksheet1.conditional_format('A1:K12', {'type': 'cell',
                                             'criteria': '=MOD(ROW(),2)',
                                             'value': 0,
                                             'format': format1})
    
    # Write another conditional format over the same range also DOES NOT WORK
    worksheet1.conditional_format('A1:K12', {'type': 'cell',
                                             'criteria': '=MOD(ROW(),2)',
                                             'value': 1,
                                             'format': format2})
    
    0 讨论(0)
提交回复
热议问题