df import to an existing excel is working correctly in jupyter but not working in VS code

huangapple go评论104阅读模式
英文:

df import to an existing excel is working correctly in jupyter but not working in VS code

问题

抱歉,你的代码片段中包含一些特殊字符和格式,无法直接翻译。如果你有任何关于代码的问题或需要帮助,请随时提出,我将尽力回答。

英文:

I have been trying to import a dataset in a excel file but code doesn't work perfectly in VS code but working perfectly in jupyter. Can anyone pls suggest where is the mistake?

my code:

  1. import pyodbc
  2. import pandas as pd
  3. from datetime import datetime
  4. import win32com.client as win32
  5. import openpyxl
  6. #SQL Server connection established
  7. cnxn = pyodbc.connect(
  8. "Driver={SQL Server};"
  9. "Server="ip";"
  10. "Database='';"
  11. "UID=Jaydeb.bhunia;"
  12. "PWD=password;"
  13. "Trused_Connection=yes")
  14. #Query executie and export csv
  15. query = pd.read_sql_query('''select top 10 * from CashOrderTrn(nolock)''',cnxn)
  16. df = pd.DataFrame(query)
  17. #Export output to local folder
  18. df.to_excel(r"C:\Users\THL1012\Desktop\Python Output\FTD_MTD_Sales.xlsx", sheet_name='Sheet1')
  19. #data import to master file
  20. book = openpyxl.load_workbook(r'C:\Users\THL1012\Desktop\Daily Alert_Automation\FTD_WTD_MTD_Sales.xlsx')
  21. df = pd.read_excel(r"C:\Users\THL1012\Desktop\Python Output\FTD_MTD_Sales.xlsx", sheet_name='Sheet1', index_col=[0,1])
  22. with pd.ExcelWriter(r"C:\Users\THL1012\Desktop\Daily Alert_Automation\FTD_WTD_MTD_Sales.xlsx", mode="w",
  23. engine="openpyxl", ) as writer:
  24. writer.book = book
  25. writer.sheets = {ws.title:ws for ws in book.worksheets}
  26. df.to_excel(writer, sheet_name='import')

答案1

得分: 1

我已经自行解决了这个问题,并分享了更改以解决进一步的问题。

  1. with pd.ExcelWriter(r"C:\Users\THL1012\Desktop\Daily Alert_Automation\FTD_WTD_MTD_Sales.xlsx", mode="w", engine="openpyxl") as writer:
  2. writer.book = book
  3. writer.sheets.update(dict((ws.title, ws) for ws in book.worksheets))
  4. df.to_excel(writer, sheet_name='import')
英文:

I have solved the issue myself, sharing the changes for further issues

  1. with pd.ExcelWriter(r"C:\Users\THL1012\Desktop\Daily Alert_Automation\FTD_WTD_MTD_Sales.xlsx", mode="w",
  2. engine="openpyxl", ) as writer:
  3. writer.book = book
  4. writer.sheets.update(dict((ws.title, ws) for ws in book.worksheets))
  5. df.to_excel(writer, sheet_name='import')

huangapple
  • 本文由 发表于 2023年6月19日 19:36:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76506237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定