简体   繁体   中英

Python code not writing output in excel sheet but is able to take input from another sheet in same workbook

Background: I am fetching Option chain for a symbol from web and then writing it to an excel sheet. I also have another excel sheet in the same workbook from which I take inputs for the program to run. All of this I am doing with excel 2016.

Sample of the code from program as the whole program is pretty long:

import xlwings as xw
excel_file = 'test.xlsx'
wb = xw.Book(excel_file)
wb.save()
# Fetching User input for Script/Ticker else it will be set to NIFTY as default
try:
    Script_Input = pd.read_excel(excel_file, sheet_name = 'Input_Options', usecols = 'C')
    script = Script_Input.iloc[0,0]
except:
    script = 'NIFTY'
# Writing data in the sheet
sht_name = script + '_OC'
    try:
        wb.sheets.add(sht_name)
        print('new sheet added')
        wb.save()
    except:
        pass
        # print('sheet already present')
    # directing pointer towards current sheet to be written
    sheet = wb.sheets(sht_name)
    sheet.range('A4').options(index = False, header = False).value = df
    sheet.range('B1').value = underlying
    sheet.range('C1').value = underlying_Value
    # sheet.range('A3').options(index = False, header = False).value = ce_data_final
    # sheet.range('J3').options(index = False, header = False).value = pe_data_final
    wb.save()

Problem: Since yesterday, I am able to open my excel workbook with excel 2016 and change inputs for my program but, I do not get any data written in the sheet that takes output from the program. The program runs perfectly as I can test the output on terminal. Also, once I delete the sheet no new sheet is being created as it should. What I tried: I have uninstalled every other version of excel I had, so now only excel 2016 is present. I have made sure that all the respective file formats use excel 2016 as the default app.

Also note that, 2 days ago I was able to write data perfectly in the respective sheet but now I am not able to do so.

Any help appreciated...

Sorry to everyone who tried to solve this question. after @buran asked about 'df' I looked into my code and found that I had a return statement before writing 'df' into sheet (I have created a separate function to write data in excel). Now that I have moved that statement to its proper place the code is working fine. I am extremely sorry as I did not realise what the problem was in the 1st place and assumed it had to do with excel and python. Now the program runs perfectly and I am getting the output I want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM