Sunday, January 8, 2023

Win32com python excel intro part 1

 import win32com.client as win32
excel=win32.gencache.EnsureDispatch('Excel.Application')
wb=excel.Workbooks.Open(r'C:\Users\allso\Desktop\new vba projects\openpyxl\countries.xlsx')
#get worksheet names        
sheet_names = [sheet.Name for sheet in wb.Sheets]
print(sheet_names)
sheet_obj=wb.Sheets('Sheet1')
print(sheet_obj)
print(sheet_obj.Name)
print(sheet_obj.Range("A1"))
cell=sheet_obj.Range("B1")
print(cell.Value2)
print(cell.Row)
print(cell.Column)
print(cell.NumberFormat)
print(cell.Address)
print(cell.AddressLocal)
print(sheet_obj.Range('A2').Value+\
      '\'s capital  '+sheet_obj.Range('B2').Value+\
      ' has a population of '+str(sheet_obj.Range('C2').Value)\
      )
print(sheet_obj.Cells(1,2))
print(sheet_obj.Cells(1,2).Value)
xlUp = -4162
print(sheet_obj.Cells(sheet_obj.Cells.Rows.Count, 1).End(xlUp).Row)
used = sheet_obj.UsedRange
nrows = used.Row + used.Rows.Count - 1
ncols = used.Column + used.Columns.Count - 1
print(nrows)
print(ncols)
for i in range(1,ncols+1):
    print(sheet_obj.Cells(1,i))
    #print(cell_obj.Value)
for i in range(1,nrows+1):
    print(sheet_obj.Cells(i,1))
    #print(cell_obj.value)
    
print(sheet_obj.Range('A1:C2'))
##for rows in sheet_obj.Range('A1:C2'):
##    
##    for cell in rows:
##        print(cell.Address,cell.Value)
##    print('--------------------------------')
for j in range(1,nrows+1):
    for i in range(1,ncols+1):
        print(sheet_obj.Cells(j,i))
    print('--------------------------------')    
wb.Close(True)
excel.Application.Quit()

No comments:

Post a Comment