How to Create Excel File in Python

This short guide describes how to create Excel file in Python by first providing information about environment configuration and then the step-by-step procedure to create, fill and save an Excel file from scratch. It will provide guidance on how by using Python create Excel file and access a particular sheet from the newly created Excel file. It also explains how to access the collection of cells to fill data in a particular cell and finally save this file in XLS or XLSX file format.

Steps to Create Excel File in Python

  1. Configure the project to install Aspose.Cells for Python via Java
  2. Instantiate a Workbook class object to create an empty Excel file
  3. Access the first Worksheet of the newly created Excel file
  4. Access the cells collection provided by default in each Worksheet
  5. Iterate through the cells collection and fill data in a few cells
  6. Save the Excel file on disk after filling in sample data

These steps describe in detail how using Python create Excel first by providing a link to the configuration and then initializing a Workbook class object. Each workbook contains a worksheet by default and each worksheet contains a collection of cells that can be used to access the individual cell to read/write data. In the end, the Excel file is saved on disk using the Save function in the workbook class object.

Code to Create an Excel File in Python

import jpype
import asposecells
# Start JVM
jpype.startJVM()
from asposecells.api import License, Workbook
# Load License
licenseHtmlToImage = License()
licenseHtmlToImage.setLicense("Aspose.Cells.lic")
# Create an instance of empty Workbook
workbook = Workbook()
# Get access to worksheets collection
worksheets = workbook.getWorksheets()
# Get a reference to the first worksheet from the worksheets collection
worksheet = worksheets.get(0)
# Set values in different cells using Cells collection
worksheet.getCells().get("C1").setValue("Value in cell C1")
worksheet.getCells().get("D1").setValue("Value in cell D1")
worksheet.getCells().get("E1").setValue("Value in cell E1")
# Autofit the columns to display complete data in columns
worksheet.autoFitColumns()
# Save the output XLSX file
workbook.save("output.xlsx")
# Shutdown the JVM
jpype.shutdownJVM()

This code imports jpype and aspose.cells, starts JVM, and then creates a new Excel file using the Workbook class object from the aspose.cells library. The collection of worksheets in a workbook contains one worksheet by default. Once the first worksheet is accessed, target cells are filled using the cells collection available in each worksheet. In the end, the workbook is saved on disk, and JVM is shut down.

To create Excel file Python language is used in this tutorial. If you want to learn other features in Python like converting Excel to PDF, refer to the article on how to convert Excel to PDF using Python.

 English