简体   繁体   English

Python win32com-将文本框中的文本读取到单元格吗?

[英]Python win32com - Read text in a text box to a cell?

I would like to read the text from a text box in an Excel File and save that value to a variable. 我想从Excel文件中的文本框中读取文本,然后将该值保存到变量中。 The problem I am having is with the reading of the TextBox. 我遇到的问题是阅读文本框。 I have tried several methods, this one showed the most promise, as it does not generate an error, but it does not elicit the desired result either. 我尝试了几种方法,这种方法显示出最大的希望,因为它不会产生错误,但是也不会引起期望的结果。 Any suggestions are appreciated. 任何建议表示赞赏。 See code below. 请参见下面的代码。

import win32com.client as win32 
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open("C:\\users\\khillstr\\Testing\\Scripts\\Book1.xlsx")
excel.Visible = False

ws = wb.Worksheets

canvas = excel.ActiveSheet.Shapes

for shp in canvas.CanvasItems:
    if shp.TextFrame.Characters:
        print shp.TextFrame.Characters
    else:
        print "no"

Canvas has to do with graphics in excel files. 画布与excel文件中的图形有关。 I think you want access to the cells. 我认为您想访问这些单元。 Below is code that prints out each row as a tuple. 下面是将每行打印为元组的代码。

import win32com.client as win32 
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open("C:\\users\\khillstr\\Testing\\Scripts\\Book1.xlsx")
excel.Visible = False

sheet = wb.Worksheets(1)

for row in sheet.UsedRange.Value:
  print row
import win32com.client as win32

file_name = 'path_to_excel'

excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(self.file_name)
excel.Visible = False

sheet = wb.Worksheets(1)
deep = lambda r,c: sheet.Cells(r,c)
print(deep(row_num,col_num))

excel.Application.Quit()

This code will open an excel located at 'path_to_excel' and read a cell located at (Row_Number = row_num, Column_Number = col_num) 此代码将打开位于“ path_to_excel”的excel,并读取位于(行编号= row_num,列编号= col_num)的单元格

要在工作表上的文本框对象中获取文本,您需要使用shp.TextFrame.Characters.Caption因为Characters方法返回的是Characters对象而不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM