openpyxl
  1. openpyxl-writing-data-to-cells

Writing Data to Cells - ( Working with Excel Files )

Heading h2

Syntax

import openpyxl

# Open an Excel file
wb = openpyxl.load_workbook('example.xlsx')

# Select a worksheet by name
ws = wb['Sheet1']

# Write data to a cell
ws['A1'] = 'Hello, World!'

# Save the changes to the Excel file
wb.save('example.xlsx')

Example

# Import the openpyxl library
import openpyxl

# Create a new Excel workbook
wb = openpyxl.Workbook()

# Select the active worksheet
ws = wb.active

# Write a header row to the worksheet
ws['A1'] = 'Name'
ws['B1'] = 'Salary'
ws['C1'] = 'Department'

# Write data to the worksheet
ws['A2'] = 'John'
ws['B2'] = 50000
ws['C2'] = 'Finance'

ws['A3'] = 'Emily'
ws['B3'] = 60000
ws['C3'] = 'HR'

# Save the changes to the Excel file
wb.save('employee_data.xlsx')

Output

The output will be a new Excel workbook with the data written to the specified cells.

Explanation

Working with Excel files is a common task in data analysis. Openpyxl is a Python module that allows you to work with Excel files in Python. To write data to an Excel file using Openpyxl, you need to create an instance of the Workbook class, select a worksheet in the workbook, and then write the data to the cells in the worksheet.

In the above example, we create a new Excel workbook using the Workbook class. We select the active worksheet in the workbook using the active property of the Workbook object. We then write the header row and the employee data to the cells in the worksheet using the index and value of the cells. Finally, we save the changes to the Excel file using the save method of the Workbook object.

Use

Writing data to cells in an Excel file is a common task in data analysis and reporting. It allows you to create reports, summarize data, and perform various calculations using the data in the Excel file.

Important Points

  • Openpyxl is a Python module for working with Excel files
  • To write data to an Excel file using Openpyxl, you need to create an instance of the Workbook class, select a worksheet in the workbook, and then write the data to the cells in the worksheet
  • You can write data to cells in an Excel worksheet using the index and value of the cells
  • You can save changes to an Excel file using the save method of the Workbook object

Summary

In conclusion, writing data to cells in an Excel file using Openpyxl is a common task in data analysis and reporting. It allows you to create reports, summarize data, and perform various calculations using the data in the Excel file. Openpyxl provides a simple and easy-to-use interface for working with Excel files in Python.

Published on: