Python Write Excel

You can write Excel files in Python using several libraries, each with its own strengths and capabilities. Here’s an overview of how to write Excel files using xlsxwriter, openpyxl, xlwt, and pyexcel.

Writing Excel Files Using openpyxl

openpyxl is a versatile library for reading and writing .xlsx files. It’s often preferred for handling .xlsx files due to its extensive feature set.

Install openpyxl

If you haven’t installed it yet:

pip install openpyxl

Example:

from openpyxl import Workbook

# Create a workbook and select the active worksheet
wb = Workbook()
ws = wb.active

# Write some data
ws['A1'] = 'Hello'
ws['B1'] = 'World'

# Write a list of data
data = [
    ['Name', 'Age', 'City'],
    ['John', 25, 'New York'],
    ['Anna', 30, 'Paris'],
    ['Mike', 22, 'London']
]

for row_idx, row in enumerate(data, start=1):
    for col_idx, value in enumerate(row, start=1):
        ws.cell(row=row_idx, column=col_idx, value=value)

# Save the workbook
wb.save('example.xlsx')

Explanation:

• Creating Workbook: Workbook() creates a new Excel file.

• Selecting Worksheet: wb.active gets the active sheet.

• Writing Data: Directly assign values to cells or use ws.cell() to write data.

• Saving Workbook: wb.save('example.xlsx') saves the file.

Writing Files Using pyexcel

pyexcel provides a simple way to read, write, and manipulate Excel files. It supports various formats and simplifies file operations.

Install pyexcel and pyexcel-xlsx

If you haven’t installed it yet:

pip install pyexcel pyexcel-xlsx

Example:

import pyexcel as pe

# Data to be written
data = [
    ['Name', 'Age', 'City'],
    ['John', 25, 'New York'],
    ['Anna', 30, 'Paris'],
    ['Mike', 22, 'London']
]

# Save the data to an Excel file
pe.save_as(array=data, dest_file_name='example.xlsx')

Explanation:

Saving Data: pe.save_as(array=data, dest_file_name='example.xlsx') saves the data to an Excel file.