Search code examples
pythonpandasexcelcplexopl

How to import data from EXCEL to PYTHON


Cplex OPL:

SheetConnection file("DATA.xlsx"); 
v from SheetRead(file, "Set1!C2:F4");
f from SheetRead(file, "Set1!C7:F9");
u1 from SheetRead(file, "Set1!C13:F16");
u2 from SheetRead(file, "Set1!J13:M16");
u3 from SheetRead(file, "Set1!P13:S16");
C from SheetRead(file, "Set1!C21:F23");
MOQ from SheetRead(file, "Set1!C27:F29");
D from SheetRead(file, "Set1!B42:D42");  
strat from SheetRead(file, "Set1!C33:F35");

The above Cplex data file describes how i import data from excel to Cplex. And i want to do the same with Python. I tried to use Pandas and i did wrong somewhere so it not worked at all.


Solution

  • dont forget to install pandas first using pip

    import pandas as pd
    
    # Load Excel file into pandas DataFrame
    df = pd.read_excel('DATA.xlsx', sheet_name='Set1', header=None)
    
    # Access data in DataFrame
    v = df.iloc[1:4, 2:6].values.tolist()
    f = df.iloc[6:9, 2:6].values.tolist()
    u1 = df.iloc[12:16, 2:6].values.tolist()
    u2 = df.iloc[12:16, 9:13].values.tolist()
    u3 = df.iloc[12:16, 15:19].values.tolist()
    C = df.iloc[20:23, 2:6].values.tolist()
    MOQ = df.iloc[26:29, 2:6].values.tolist()
    D = df.iloc[41, 1:4].tolist()
    strat = df.iloc[32:35, 2:6].values.tolist()
    
    # Print data
    print(v)
    print(f)
    print(u1)
    print(u2)
    print(u3)
    print(C)
    print(MOQ)
    print(D)
    print(strat)