divesh
divesh

Reputation: 71

How do I create a new excel sheet dynamically using python?

I want to create a excel sheet which doesnt exist till now dynamically on runtime. I dont want to add sheets in excel sheet but I want to create a whole new excel file with the name of a random unique id created at runtime. Is there any chance I can do that using openpyxl or any other library in python. Your any help will be appreciated. Thank you

Upvotes: 0

Views: 2897

Answers (1)

Jadon Manilall
Jadon Manilall

Reputation: 637

Absolutely!

First you need the required libraries. Personally, I've use the following combination libraries - and in my experience, they work exactly as expected.

  1. Pandas: pip install pandas
  2. XlsxWriter: pip install XlsxWriter
  3. Xlrd (optional - used for reading in excel files): pip install xlrd

Once you have them installed, you can adapt the following code snippet (taken from XlsxWriter's docs) to your requirements.

import pandas as pd

# Create a Pandas dataframe from the data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})

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

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

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

Upvotes: 4

Related Questions