,

Create Slicing Functionality in Excel Using Python Automation

Creating slicing functionality in Excel using Python allows you to extract and display specific subsets of data from a larger dataset. This functionality is useful for analyzing and visualizing data based on different criteria, such as regions, categories, or any other relevant factors. By automating this process with Python, you can efficiently manage and present your data in a way that is easy to understand and work with.

Let us take an example to understand how you can create a slicer automatically with python in for your excel sheet

We have to Write automated code in python to create a excel sheet first and add data to columns name, sales and region excel sheet and slice dates from it.. Like south, east and west slice these three in a new set of box and whenever I click on south it should show me only south region sales and names along with region name

To achieve this, you can use the openpyxl library in Python for creating and manipulating Excel files. First, install the openpyxl library if you haven’t already:

pip install openpyxl

So first we create an Excel sheet, add data to columns (name, sales, region), and then create slicers for the region

import pandas as pd

# Create a DataFrame
data = {
    'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank'],
    'sales': [100, 150, 200, 120, 180, 220],
    'region': ['South', 'East', 'West', 'South', 'East', 'West']
}
df = pd.DataFrame(data)

# Create an Excel writer object
with pd.ExcelWriter('sales_data.xlsx') as writer:
    # Write the DataFrame to the Excel sheet
    df.to_excel(writer, index=False, sheet_name='Sheet1')

# Read the Excel file
df = pd.read_excel('sales_data.xlsx')

# Create a slicer DataFrame
slicer_data = {
    'South': df[df['region'] == 'South'],
    'East': df[df['region'] == 'East'],
    'West': df[df['region'] == 'West']
}

# Create a function to display the sliced data
def display_sliced_data(region):
    print(slicer_data[region])

# Example: Display South region data
display_sliced_data('South')

In the above code we have a excel sheet created sales_data.xlsx and then we are creating a slicer dataframe which is slicer_data. At last the slicer function display_sliced_data to dispaly the sliced data in the same excel sheet.

Output:

This code creates an Excel sheet with sales data and regions. It then reads the Excel file and creates a slicer functionality for South, East, and West regions. The display_sliced_data function allows you to display the sales data for a specific region when called with the region name as an argument.

Now, if you want to first open the original excel sheet with the data and then show the excel sheet adding sliced data. You can write the below code for that

import pandas as pd

# Create a DataFrame with sample data
data = {
    'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank'],
    'sales': [100, 150, 200, 120, 180, 220],
    'region': ['South', 'East', 'West', 'South', 'East', 'West']
}
df = pd.DataFrame(data)

# Write the DataFrame to an Excel file
df.to_excel('sales_data.xlsx', index=False)

# Read the Excel file
df = pd.read_excel('sales_data.xlsx')

# Create a new Excel writer object
with pd.ExcelWriter('sales_data_sliced.xlsx', engine='xlsxwriter') as writer:
    # Write the original data to a new sheet
    df.to_excel(writer, sheet_name='Original', index=False)

    # Slice the data based on region
    for region in df['region'].unique():
        region_df = df[df['region'] == region]
        region_df.to_excel(writer, sheet_name=region, index=False)

print("Excel file with sliced data created successfully.")

In the above code , when you run it form the terminal. It will show you a message Excel file with sliced data created successfully. Then you can open from the path the file name sales_data_xlsx to see the output

Output:

Explanation of each line of code:

  1. import pandas as pd: Imports the pandas library with the alias pd, which is a popular library for data manipulation and analysis in Python.
  2. data = { 'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank'], 'sales': [100, 150, 200, 120, 180, 220], 'region': ['South', 'East', 'West', 'South', 'East', 'West'] }: Creates a dictionary data containing sample data for names, sales, and regions.
  3. df = pd.DataFrame(data): Creates a DataFrame df from the data dictionary, which organizes the data into rows and columns, similar to a spreadsheet.
  4. df.to_excel('sales_data.xlsx', index=False): Writes the DataFrame df to an Excel file named 'sales_data.xlsx', without including the DataFrame index.
  5. df = pd.read_excel('sales_data.xlsx'): Reads the Excel file 'sales_data.xlsx' into a new DataFrame df.
  6. with pd.ExcelWriter('sales_data_sliced.xlsx', engine='xlsxwriter') as writer:: Creates a new Excel file 'sales_data_sliced.xlsx' using pd.ExcelWriter with the xlsxwriter engine. The with statement ensures that the writer is properly closed after use.
  7. df.to_excel(writer, sheet_name='Original', index=False): Writes the original DataFrame df to a new sheet named 'Original' in the Excel file.
  8. for region in df['region'].unique():: Iterates over the unique values in the 'region' column of the DataFrame.
  9. region_df = df[df['region'] == region]: Creates a new DataFrame region_df containing only the rows where the 'region' column matches the current region.
  10. region_df.to_excel(writer, sheet_name=region, index=False): Writes the sliced DataFrame region_df to a new sheet in the Excel file, using the current region as the sheet name.
  11. print("Excel file with sliced data created successfully."): Prints a message indicating that the Excel file with sliced data has been created successfully.

More on Python automation with Excel

In conclusion,

Python provides powerful tools like pandas and xlsxwriter to automate tasks in Excel, making it easier to manipulate and analyze data. By using these tools, you can create custom solutions such as slicing functionality, which allows you to extract and organize data based on specific criteria. This automation not only saves time but also ensures accuracy and consistency in your data analysis workflows.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>