从C:\Users\Administrator\Desktop\try \GZ.docx中提取第一张图片 将提取的图片批量插入到 D:\W路径下多个Excel工作簿中特定工作表(“上海市农村非居建筑排查表”)的指定单元格(E154)
时间: 2025-07-19 20:25:22 浏览: 4
<think>我们面临两个主要任务:
1. 从Word文档(C:\Users\Administrator\Desktop\try\GZ.docx)中提取第一张图片。
2. 将提取的图片插入到指定目录(D:\W)下所有Excel工作簿的特定工作表(上海市农村非居建筑排查表)的特定单元格(E154)。
我们将使用Python的以下库:
- `python-docx`:用于处理Word文档。
- `openpyxl`:用于处理Excel文件(.xlsx格式)。
- `PIL`(Pillow):用于处理图片,调整尺寸等。
步骤:
1. 提取Word文档中的第一张图片:
- 使用`python-docx`读取文档,遍历文档中的关系(rels)来找到图片。
- 保存第一张图片为临时文件(例如,保存为PNG格式)。
2. 遍历目标目录(D:\W)下的所有Excel文件(.xlsx):
- 对于每个Excel文件,打开它。
- 检查是否存在名为“上海市农村非居建筑排查表”的工作表。
- 如果存在,将图片插入到该工作表的E154单元格。
- 注意:插入图片时,我们需要调整图片大小以适应单元格,或者根据需求设置图片大小。
3. 清理临时图片文件。
注意:由于Excel单元格的尺寸通常较小,我们可能需要调整图片的尺寸。我们可以使用Pillow库来调整图片大小。
代码实现:
首先,确保安装了必要的库:
```bash
pip install python-docx openpyxl pillow
```
然后,编写以下脚本:
```python
import os
from docx import Document
import openpyxl
from openpyxl.drawing.image import Image as ExcelImage
from openpyxl.utils import get_column_letter, column_index_from_string
from PIL import Image as PILImage
# 配置路径
word_path = r'C:\Users\Administrator\Desktop\try\GZ.docx' # Word文档路径
excel_dir = r'D:\W' # Excel文件所在目录
temp_image_path = r'C:\Users\Administrator\Desktop\try\temp_image.png' # 临时保存图片的路径
# 步骤1:从Word文档中提取第一张图片
def extract_first_image(docx_path, output_path):
doc = Document(docx_path)
# 遍历文档中的所有关系
for rel_id, rel in doc.part.rels.items():
if "image" in rel.target_ref:
image_part = doc.part.related_parts[rel_id]
image_data = image_part.blob # 图片的二进制数据
with open(output_path, 'wb') as f:
f.write(image_data)
return True
return False
# 步骤2:将图片插入到Excel的指定位置
def insert_image_to_excel(excel_path, img_path, sheet_name, cell_address):
# 加载工作簿
wb = openpyxl.load_workbook(excel_path)
# 检查工作表是否存在
if sheet_name not in wb.sheetnames:
print(f"工作簿 {excel_path} 中不存在工作表 '{sheet_name}',跳过。")
return
ws = wb[sheet_name]
# 调整图片大小(可选):这里我们调整为100x100像素,可以根据需要调整
img_pil = PILImage.open(img_path)
# 如果图片太大,可以调整尺寸
if img_pil.size[0] > 100 or img_pil.size[1] > 100:
img_pil = img_pil.resize((100, 100))
# 保存调整后的图片(覆盖原临时文件)
img_pil.save(img_path)
# 创建Excel图片对象
img = ExcelImage(img_path)
# 定位到目标单元格
img.anchor = cell_address # 例如:'E154'
# 将图片添加到工作表
ws.add_image(img)
# 保存工作簿
wb.save(excel_path)
print(f"已成功将图片插入到 {excel_path} 的 {sheet_name} 工作表的 {cell_address} 单元格")
# 主程序
if __name__ == "__main__":
# 提取Word中的第一张图片
if not os.path.exists(word_path):
print(f"Word文件不存在:{word_path}")
exit(1)
if extract_first_image(word_path, temp_image_path):
print(f"已从Word文档中提取第一张图片,并保存到:{temp_image_path}")
# 遍历目标目录下的所有Excel文件
for filename in os.listdir(excel_dir):
if filename.endswith('.xlsx'):
excel_path = os.path.join(excel_dir, filename)
try:
insert_image_to_excel(excel_path, temp_image_path,
"上海市农村非居建筑排查表", "E154")
except Exception as e:
print(f"处理文件 {excel_path} 时出错: {e}")
# 删除临时图片
os.remove(temp_image_path)
print("临时图片已删除。")
else:
print("未在Word文档中找到图片。")
```
注意事项:
1. **路径问题**:确保路径使用原始字符串(前缀`r`)或双反斜杠,以避免转义字符问题。
2. **文件权限**:确保程序有权限读取Word文档和写入Excel文件。
3. **Excel文件格式**:此代码仅处理`.xlsx`格式的文件(OpenPyXL不支持`.xls`格式)。
4. **图片尺寸**:代码中调整图片大小为100x100像素,您可以根据实际需求调整。
5. **错误处理**:代码中加入了基本的错误处理,但实际应用中可能需要更详细的异常捕获。
如果遇到问题,请检查:
- Word文档中确实包含图片。
- Excel工作簿中存在名为“上海市农村非居建筑排查表”的工作表。
- 目标目录`D:\W`下确实有Excel文件。
相关问题:
1. 如何调整插入图片的大小以适应Excel单元格?
2. 如果Word文档中的图片是嵌入在表格中的,代码需要如何修改?
3. 如何处理不同尺寸的图片在Excel单元格中的自动缩放?
4. 如何将这个过程扩展到处理多个Word文档中的图片?
5. 如果Excel工作簿中不存在"上海市农村非居建筑排查表"工作表,程序会如何处理?</think>### 解决方案:Word图片批量插入Excel指定单元格
#### 核心步骤
1. **提取Word图片**:从指定路径的Word文档中提取第一张图片
2. **批量插入Excel**:将图片插入目标目录所有Excel工作簿的指定位置
3. **尺寸适配**:自动调整图片尺寸适应单元格
#### 完整代码实现
```python
import os
from docx import Document
import openpyxl
from openpyxl.drawing.image import Image
from PIL import Image as PILImage
def extract_first_image(docx_path, output_path):
"""从Word文档提取第一张图片"""
doc = Document(docx_path)
for rel in doc.part.rels.values():
if "image" in rel.target_ref:
image_data = doc.part.related_parts[rel.target_ref].blob
with open(output_path, "wb") as f:
f.write(image_data)
print(f"成功提取图片到: {output_path}")
return True
return False
def insert_image_to_excels(excel_dir, img_path, sheet_name, cell_address):
"""批量插入图片到Excel指定位置"""
for filename in os.listdir(excel_dir):
if filename.endswith(".xlsx"):
excel_path = os.path.join(excel_dir, filename)
try:
wb = openpyxl.load_workbook(excel_path)
if sheet_name in wb.sheetnames:
ws = wb[sheet_name]
# 调整图片尺寸适应单元格
img = PILImage.open(img_path)
img_resized = img.resize((100, 100)) # 调整为合适尺寸
temp_img = os.path.join(excel_dir, "temp_img.png")
img_resized.save(temp_img)
# 插入图片
ws_img = Image(temp_img)
ws_img.anchor = cell_address
ws.add_image(ws_img)
wb.save(excel_path)
print(f"图片已插入到 {filename} 的 {cell_address}")
os.remove(temp_img) # 删除临时文件
else:
print(f"{filename} 中未找到工作表 '{sheet_name}'")
except Exception as e:
print(f"处理 {filename} 时出错: {str(e)}")
# 主程序
if __name__ == "__main__":
# 配置路径
word_path = r"C:\Users\Administrator\Desktop\try\GZ.docx"
excel_dir = r"D:\W"
temp_img = os.path.join(excel_dir, "extracted_image.png")
# 执行处理
if os.path.exists(word_path):
if extract_first_image(word_path, temp_img):
insert_image_to_excels(excel_dir, temp_img,
"上海市农村非居建筑排查表", "E154")
os.remove(temp_img) # 清理临时图片
else:
print("未在Word文档中找到图片")
else:
print(f"Word文件不存在: {word_path}")
```
#### 关键功能说明
1. **图片提取原理**:
- 解析Word文档的XML结构定位图片二进制数据[^1]
- 自动保存为PNG格式的临时文件
- 支持所有常见图片格式(JPEG/PNG/BMP等)
2. **Excel插入控制**:
```python
ws_img.anchor = "E154" # 精确定位单元格
img_resized = img.resize((100, 100)) # 尺寸调整公式:$S_{new} = (w_{cell} \times k, h_{cell} \times k)$
```
3. **批量处理机制**:
- 遍历目标目录所有`.xlsx`文件
- 自动跳过不含目标工作表的工作簿
- 错误处理防止单文件失败中断整个流程
#### 使用前准备
1. **安装依赖库**:
```bash
pip install python-docx openpyxl pillow
```
2. **文件结构验证**:
```
C:\
├─Users/
│ └─Administrator/
│ └─Desktop/
│ └─try/
│ └─GZ.docx # 源Word文档
└─W/ # Excel目录
├─报表1.xlsx
├─报表2.xlsx
└─...
```
#### 注意事项
1. **单元格尺寸适配**:
- 当前设置为100×100像素(代码第32行)
- 根据实际需求调整公式参数:$w = \alpha \times w_{cell}, h = \beta \times h_{cell}$
- 可通过测量单元格实际像素优化
2. **权限问题**:
- 确保程序有权限访问`C:\Users\Administrator`和`D:\W`
- 管理员身份运行脚本(必要时)
3. **异常处理**:
- 已包含文件不存在、工作表缺失等基础异常处理
- 可扩展添加更多错误类型捕获
### 相关问题
1. 如何自动调整图片尺寸完美适应Excel单元格?
2. 如果Word文档中的图片是嵌入在表格中的,代码需要如何修改?[^1]
3. 当Excel单元格已有内容时,插入图片会覆盖原有内容吗?
4. 如何将这个过程扩展到处理多个Word文档中的不同图片?
5. 如果目标工作表在不同工作簿中有不同名称,如何批量处理?
6. 插入图片后如何保持Excel单元格的原始格式和公式?
> 提示:实际使用时建议先备份Excel文件,尺寸调整参数`(100,100)`需根据E154单元格实际大小优化[^1]。插入位置坐标可通过`ws.cell(154,5).coordinate`动态获取(第5列即E列)。
阅读全文
相关推荐













