I would like to read the text from a text box in an Excel File and save that value to a variable. The problem I am having is with the reading of the TextBox. I have tried several methods, this one showed the most pro开发者_运维问答mise, 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. 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
To get the text in a textbox object on a sheet you need to use shp.TextFrame.Characters.Caption
as the Characters
method returns a Characters
object and not a string.
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)
精彩评论