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

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

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:

import pyodbc
import pandas as pd
from datetime import datetime
import win32com.client as win32
import openpyxl

#SQL Server connection established

cnxn = pyodbc.connect(
    "Driver={SQL Server};"
    "Server="ip";"
    "Database='';"
    "UID=Jaydeb.bhunia;"
    "PWD=password;"
    "Trused_Connection=yes")

#Query executie and export csv
query = pd.read_sql_query('''select top 10 * from CashOrderTrn(nolock)''',cnxn)
df = pd.DataFrame(query)

#Export output to local folder
df.to_excel(r"C:\Users\THL1012\Desktop\Python Output\FTD_MTD_Sales.xlsx", sheet_name='Sheet1')

#data import to master file
book = openpyxl.load_workbook(r'C:\Users\THL1012\Desktop\Daily Alert_Automation\FTD_WTD_MTD_Sales.xlsx')
df = pd.read_excel(r"C:\Users\THL1012\Desktop\Python Output\FTD_MTD_Sales.xlsx", sheet_name='Sheet1', index_col=[0,1])

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

答案1

得分: 1

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

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

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

with pd.ExcelWriter(r"C:\Users\THL1012\Desktop\Daily Alert_Automation\FTD_WTD_MTD_Sales.xlsx", mode="w",
                    engine="openpyxl", ) as writer:
    writer.book = book
    writer.sheets.update(dict((ws.title, ws) for ws in book.worksheets))
    
    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:

确定