You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
# pip install pywin32
|
|
|
|
|
# https://blog.csdn.net/weixin_42927998/article/details/115086797
|
|
|
|
|
|
|
|
|
|
import win32com
|
|
|
|
|
from openpyxl import Workbook
|
|
|
|
|
from win32com.client import constants
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
# 文件路径
|
|
|
|
|
taskPath = r'c:/task.txt'
|
|
|
|
|
# 读取文件,第一行是docx路径,第二行是第几个图表
|
|
|
|
|
with open(taskPath, 'r', encoding='utf-8') as f:
|
|
|
|
|
docPath = f.readline().strip()
|
|
|
|
|
tuBiaoNum = int(f.readline().strip())
|
|
|
|
|
|
|
|
|
|
docApp = win32com.client.Dispatch('Word.Application')
|
|
|
|
|
# 是否显示Word文档
|
|
|
|
|
docApp.Visible = True
|
|
|
|
|
docApp.DisplayAlerts = 0
|
|
|
|
|
|
|
|
|
|
doc = docApp.Documents.Open(docPath)
|
|
|
|
|
# 初始化数据列表
|
|
|
|
|
data = []
|
|
|
|
|
|
|
|
|
|
# 遍历文档中的所有内嵌形状
|
|
|
|
|
idx = 1
|
|
|
|
|
for inline_shape in doc.InlineShapes:
|
|
|
|
|
if inline_shape.Type == constants.wdInlineShapeChart: # 检查是否为内嵌图表
|
|
|
|
|
|
|
|
|
|
if idx == tuBiaoNum:
|
|
|
|
|
shape = doc.InlineShapes(idx)
|
|
|
|
|
sheet = shape.Chart.ChartData.Workbook.Worksheets("Sheet1")
|
|
|
|
|
# 行数
|
|
|
|
|
row_size = sheet.UsedRange.Rows.Count
|
|
|
|
|
# 列数
|
|
|
|
|
col_size = sheet.UsedRange.Columns.Count
|
|
|
|
|
|
|
|
|
|
# 读取数据
|
|
|
|
|
for i in range(1, row_size + 1):
|
|
|
|
|
row_data = []
|
|
|
|
|
for j in range(1, col_size + 1):
|
|
|
|
|
row_data.append(sheet.Cells(i, j).Value)
|
|
|
|
|
data.append(row_data)
|
|
|
|
|
break
|
|
|
|
|
# 下一个图表的索引号
|
|
|
|
|
idx = idx + 1
|
|
|
|
|
|
|
|
|
|
# 关闭文档和Word应用
|
|
|
|
|
doc.Close()
|
|
|
|
|
docApp.Quit()
|
|
|
|
|
|
|
|
|
|
# 创建一个新的工作簿
|
|
|
|
|
wb = Workbook()
|
|
|
|
|
|
|
|
|
|
# 选择默认的工作表
|
|
|
|
|
ws = wb.active
|
|
|
|
|
|
|
|
|
|
# 将数据写入工作表
|
|
|
|
|
for row in data:
|
|
|
|
|
ws.append(row)
|
|
|
|
|
|
|
|
|
|
# 保存工作簿到文件
|
|
|
|
|
wb.save("C:/task.xlsx")
|