Search code examples
pythonexcelwin32com

Read multiple lines in a single excel cell using python


Is there a way to read multiple lines in a single excel cell, line by line. I need this for accessing the signal names and its values

Let say the below three lines are in one excel cell

Signal1: 20

signal2: 30

signal3: 40

I want to access these, line by line separately to fetch the signal name and its value using python win32com. I can do it by if these lines are in individual cells but, I cant go with this method, as there is some dependency.

Any help would be really appreciated.


Solution

  • The cell will be returned as a single string with \n characters for each line. As such, a standard Python split can be used to give you a list of lines:

    import win32com.client as win32
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    
    wb = excel.Workbooks.Open(r"E:\Python temp\example.xls")
    ws = wb.Worksheets("Sheet 1")
    print ws.Range("A1").Value.split('\n')
    excel.Application.Quit()
    

    Giving something like:

    [u'Signal1: 20', u'signal2: 30', u'signal3: 40']