英文:
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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论