Python Forum
Pandas keep existing format of Excel
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pandas keep existing format of Excel
#1
Hello everybody,

I've written a little Python Script which loads an Excel file and picks random entries basend on a few criteria. Those entries are then written to a python list. The status of those entries needs to be changed afterwards in my excel. This works as planned.
But when the data is written to Excel my custom formatting (Alignment of all rows, text- and row colours are all set back to white, etc.) is gone. So this brings me to my question, how can i save to Excel with pandas while keeping my original formating?

This is my code so far:

#!/usr/bin/env Python3

# Imports
import pandas as pd
import random
import sys

def main():
    # Load Information From Excel
    df = pd.read_excel('config/Mappe1.xlsx')

    try:
        # Create List
        random_names = []

        # Get Random Task Entries
        for i in [{"description": "Value Below 800", "start_number": 0, "end_number": 800, "amount": 2}, {"description": "Value Above 800", "start_number": 801, "end_number": 10000, "amount": 1}]:
            # Criteria Are Checked
            entries = df.query(f"`Category` == 'Tasks' and `Status` == 'Open' and {i['start_number']} <= `Value` <= {i['end_number']}")[['Name', 'Value']].values.tolist()

            # Select Random Names and Append to List
            selected_entries = random.sample(entries, i['amount'])
            random_names.extend(selected_entries)

        # Change Information in DataFrame
        for name, follower in random_names:
            df.loc[df['Name'] == name, 'Status'] = 'Done'

        # Save Information to Excel
        df.to_excel('config/Mappe1.xlsx', index=False)

    except Exception as e:
        print(e)

# Start Main Function
main()

# End
sys.exit()
Reply
#2
Pandas knows nothing about excel formatting, but you can add formatting when you write a dataframe to an excel file. This is done by making a custom xlsx writer. XlsxWriter is a package for making custom "writers" that can be passed to to_excel().

If you know what cells changed, you can use a package like Openpyxl to open the existing excel file and modify the data of the cells, leaving the formatting alone. Looking at your example I don't see where you are getting any benefit from using Pandas. Maybe you could open the spreadheet using openpyxl, make all the changes using regular python code, and write the modified spreadsheet.

I'm a bit confused about this:
    except Exception as e:
        print(e)
This extra code only results in getting less information about errors that occur.
# End
sys.exit()
This just results in your program raising an exception and ending. Your program will end anyway because there are no instructions left to execute.
Reply
#3
When using pandas to write data back to an Excel file, you can lose the formatting because the default behavior is to only write the data, not the formatting information. To preserve the formatting, you can use the openpyxl library in conjunction with pandas. This library allows you to load an existing workbook, modify its content, and save it, preserving the original formatting. doodle baseball
#!/usr/bin/env Python3

# Imports
import pandas as pd
import openpyxl
import random
import sys

def main():
    # Load Information From Excel
    df = pd.read_excel('config/Mappe1.xlsx', engine='openpyxl')

    try:
        # Create List
        random_names = []

        # Get Random Task Entries
        for i in [{"description": "Value Below 800", "start_number": 0, "end_number": 800, "amount": 2}, {"description": "Value Above 800", "start_number": 801, "end_number": 10000, "amount": 1}]:
            # Criteria Are Checked
            entries = df.query(f"`Category` == 'Tasks' and `Status` == 'Open' and {i['start_number']} <= `Value` <= {i['end_number']}")[['Name', 'Value']].values.tolist()

            # Select Random Names and Append to List
            selected_entries = random.sample(entries, i['amount'])
            random_names.extend(selected_entries)

        # Change Information in DataFrame
        for name, follower in random_names:
            df.loc[df['Name'] == name, 'Status'] = 'Done'

        # Save Information to Excel with openpyxl
        with pd.ExcelWriter('config/Mappe1.xlsx', engine='openpyxl') as writer:
            writer.book = openpyxl.load_workbook('config/Mappe1.xlsx')
            df.to_excel(writer, sheet_name='Sheet1', index=False)

    except Exception as e:
        print(e)

# Start Main Function
main()

# End
sys.exit()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  xlswriter(pandas) and conditional format paul18fr 1 1,170 Aug-28-2022, 07:56 AM
Last Post: paul18fr
  [Pandas] Write data to Excel with dot decimals manonB 1 5,916 May-05-2021, 05:28 PM
Last Post: ibreeden
  Python - Merge existing cells of Excel file created with xlsxwriter manonB 0 3,732 Mar-10-2021, 02:17 PM
Last Post: manonB
  Python PDF merging from an excel pandas for loop siraero 0 2,205 Aug-16-2020, 09:34 AM
Last Post: siraero
  Need Help With Filtering Data For Excel Files Using Pandas eddywinch82 9 6,169 Aug-06-2019, 03:44 PM
Last Post: eddywinch82
  How to use the excel filename as a value to populate new column, using Pandas? Dequanharrison 5 6,545 Jun-26-2019, 11:11 PM
Last Post: Dequanharrison
  pandas change row value an existing column with conditionals Gigux 1 2,974 Jun-22-2019, 08:04 PM
Last Post: Gigux
  pandas writing to excel .. help anna 0 2,101 Jun-20-2019, 06:34 AM
Last Post: anna
  How to add a dataframe to an existing excel file wendysling 2 28,191 May-09-2019, 07:00 PM
Last Post: wendysling
  Pandas melt only on one variable (leaving other in long format) amyd 0 1,964 May-08-2019, 12:10 PM
Last Post: amyd

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020