Python Openpyxl: Insert Text File as Attachment into Excel Cell
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:
- Install Openpyxl: If you don't have it already, install the Openpyxl library using pip:
pip install openpyxl
- Import Libraries: Import the necessary functions from the Openpyxl library:
from openpyxl import load_workbook
- Load Excel File: Load the existing Excel file (1.xlsx):
workbook = load_workbook('1.xlsx')
- Access Worksheet: Get the first sheet (sheet1) from the workbook:
sheet = workbook.active
- 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()
- Write to Cell: Write the text content to the specified cell (H8):
sheet['H8'] = attachment_content
- 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.txtfile and the Python script in the same directory. - Ensure the Excel file is named
1.xlsxand 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.
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qugT 著作权归作者所有。请勿转载和采集!