Home Β» excel Β» Python – Working with Excel – Enter data everytime 9 cells at a time

Python – Working with Excel – Enter data everytime 9 cells at a time

Posted by: admin April 23, 2020 Leave a comment


Hey Guys I am re writing my question with code, First of all I am new to programming. Started to think about programming recently. πŸ™ at very later stage of life πŸ™‚

My code is as below:

   import win32com.client as win32
   from win32com.client import Dispatch

   excel = win32.gencache.EnsureDispatch('Excel.Application')
   wb = excel.Workbooks.Open(r'F:\python\book1.xlsx')
   excel.Visible = False
   ws = wb.Worksheets("Sheet1")

   # to get the last row 
   used = ws.UsedRange
   nrows = used.Row + used.Rows.Count

   ws.Cells(nrows,2).Value = "21"
   ws.Cells(nrows,2).Offset(2,1).Value = "22"
   ws.Cells(nrows,2).Offset(3,1).Value = "23"
   #like this nine values


What I am trying to do is write values in the excel sheet.

sample sheet

Old Question Below Ignore it.
I am using Python 2.7 and win32com to access excel file

I am stuck with a problem where I need to enter data in to 9 cells each time on column B

I want to select the last cell in B column and enter the new set of 9 cell values.

I tried to use ws.usedRange but this is not helping as it chooses the last cell wherever the data is present in the whole sheet. You can see in the attached sheet testdata which is spread in columns D,E,F etc so used range chooses the last cell based on that. is there a way to solve my problem? I am ok to use any other module as well if it helps.


How to&Answers:

A UsedRange:

… includes any cell that has ever been used. For example, if cell A1 contains a value, and then you delete the value, then cell A1 is considered used. In this case, the UsedRange property will return a range that includes cell A1.

Do you want to work on every cell that has ever been used? If not, why would you use UsedRange? If so, what are you trying to use it for? To find the last row in the UsedRange? You can do that easily. The Range Objects docs show you what you can do with them.

Then, once you know what you want to specify, the same documentation shows how to ask for it. You want B10:B18? Just ws.Range('B10:B18').

Once you have that Range object, you can assign a value or formula to the whole range, iterate over its cells, etc. Again, the same docs show how to do it.