在Python中从Excel获取形状内的文本框值

问题描述 投票:0回答:1

我正在开发一个功能,允许用户将

.xls
.xlsx
文件上传到服务器并将这些文件中的数据保存到数据库中。

我正在使用

openpyxl
xlrd
库从 Excel 读取数据,但对于某些在形状内包含教科书文本的 Excel 文件,我目前无法读取这些值。

我知道也许我的问题与此重复:Obtain textbox value from Excel in Python但是该问题提出者的解决方案不是通用解决方案。

有人知道如何实现这一目标吗?

python excel pandas openpyxl xlrd
1个回答
0
投票

导入 win32com.client

def extract_shape_text(输入文件,工作表名称): # 打开 Excel 应用程序 excel = win32com.client.Dispatch("Excel.Application") # 打开工作簿 工作簿 = excel.Workbooks.Open(input_file) # 选择工作表 工作表 = 工作簿.Sheets(sheet_name)

# Iterate over shapes to find the one named 'conclusion' and print its text
for shape in sheet.Shapes:
    if shape.Name == 'conclusion':
        print(f"Shape Name: {shape.Name}")
        try:
            text = shape.TextFrame.Characters().Text
            print(f"Text inside the shape: {text}")
        except:
            print("The shape does not contain any text or an error occurred.")
        break

# Close the workbook
workbook.Close(SaveChanges=False)
# Quit Excel application
excel.Quit()

input_file = r'输入文件路径' sheet_name = "工作表名称" extract_shape_text(输入文件,工作表名称)

© www.soinside.com 2019 - 2024. All rights reserved.