This guide will show you how to use the Openpyxl library in Python to insert the content of a text file (A.txt) as an attachment into a specific cell (H8) within a pre-existing Excel file (1.xlsx). It's important to note that this process will actually insert the text content into the cell, not an actual attached file.

Steps:

  1. Install Openpyxl: If you don't have it already, install the Openpyxl library using pip:
pip install openpyxl
  1. Import Libraries: Import the necessary functions from the Openpyxl library:
from openpyxl import load_workbook
  1. Load Excel File: Load the existing Excel file (1.xlsx):
workbook = load_workbook('1.xlsx')
  1. Access Worksheet: Get the first sheet (sheet1) from the workbook:
sheet = workbook.active
  1. Read Text File: Open and read the content of the text file (A.txt):
with open('A.txt', 'r') as file:
    attachment_content = file.read()
  1. Write to Cell: Write the text content to the specified cell (H8):
sheet['H8'] = attachment_content
  1. Save Changes: Save the modified Excel file:
workbook.save('1.xlsx')

Complete Code:

from openpyxl import load_workbook

# Load Excel file
workbook = load_workbook('1.xlsx')

# Access worksheet
sheet = workbook.active

# Read text file
with open('A.txt', 'r') as file:
    attachment_content = file.read()

# Write to cell
sheet['H8'] = attachment_content

# Save changes
workbook.save('1.xlsx')

Important:

  • Place the A.txt file and the Python script in the same directory.
  • Ensure the Excel file is named 1.xlsx and is also in the same directory.

Running this script will insert the content of the A.txt file into the H8 cell of the 1.xlsx sheet1.

Python Openpyxl: Insert Text File as Attachment into Excel Cell