使用python将SQL输出数据更新到相应工作表中的现有Excel

我是Python新手,寻求一些帮助/指导来纠正我的Python代码。

在这里我的查询是。

  1. 我有一个Excel文件(7 Tabs)。
  2. 我有一个文件夹,其中包含7个不同的文本文件,每个文本文件包含相应的选项卡SQL查询,每个文本文件名称与Excel文件中可用的选项卡名称相同。

我写了一个Python代码循环遍历所有的文本文件,并执行每个文本文件SQL查询和任何数据将在输出输出数据应该转储到相应的工作表/选项卡中现有的Excel文件。 我使用pandas来做到这一点,但是,代码工作正常,但更新数据到Excel大pandas是从文件中删除所有现有的工作表,并只更新当前输出数据到Excel文件。

例如:如果Python代码执行一个文本文件(文件名:数据),执行这个SQL查询后,我们得到了一些数据,这些数据应该转储到Excel文件(sheetname:Data)中。

<pre><code> import pypyodbc import pandas as pd import os import ctypes from pandas import ExcelWriter fpath = r"C:\MNaveed\DataScience\Python Practice New\SQL Queries" xlfile = r"C:\MNaveed\DataScience\Python Practice New\SQL Queries\Open_Case_Data.xlsx" cnxn = pypyodbc.connect('Driver={SQL Server};Server=MyServerName;Database=MyDatabaseName;Trusted_Connection=Yes') cursor = cnxn.cursor() for subdir, dirs, files in os.walk(fpath): for file in files: #print(os.path.join(subdir,file)) filepath = os.path.join(subdir,file) #print("FilePath: ", filepath) if filepath.endswith(".txt"): if file != "ClosedAging_Cont.txt": txtdata = open(filepath, 'r') script = txtdata.read().strip() txtdata.close() cursor.execute(script) if file == "ClosedAging.txt": txtdata = open(os.path.join(subdir,"ClosedAging_Cont.txt"), 'r') script = txtdata.read().strip() txtdata.close() cursor.execute(script) col = [desc[0] for desc in cursor.description] data = cursor.fetchall() df = pd.DataFrame(list(data),columns=col) #save_xls(df,xlfile) writer = pd.ExcelWriter(xlfile) flnm = file.replace('.txt','').strip() df.to_excel(writer,sheet_name=flnm,index=False) writer.save() print(file, " : Successfully Updated.") else: print(file, " : Ignoring this File") else: print(file, " : Ignoring this File") ctypes.windll.user32.MessageBoxW(0,"Open Case Reporting Data Successfully Updated","Open Case Reporting",1) </pre></code> 

通过循环访问文本文件,每次都会覆盖循环中的Excel文件。 而是实例化pd.ExcelWriter(xlfile)并在循环外部调用writer.save()。

以下示例是从xlswriter文档改编的

您可以在这里find更多有关多个工作表的信息: xlswriter文档 – 多个工作表

 import pandas as pd # Create a Pandas Excel writer using XlsxWriter as the engine outside the loop. writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter') # Sample loop, replace with directory browsing loop for i in range(7): # Sample Pandas dataframe. Replace with SQL query and resulting data frame. df = pd.DataFrame({'DataFromSQLQuery': ['SQL query result {0}'.format(i)]}) # Convert the dataframe to an XlsxWriter Excel object. df.to_excel(writer, sheet_name='Sheet{0}'.format(i)) # Close the Pandas Excel writer and output the Excel file. writer.save() 

以下代码解决了具体的问题,但未经testing。

 import pypyodbc import pandas as pd import os import ctypes from pandas import ExcelWriter fpath = r"C:\MNaveed\DataScience\Python Practice New\SQL Queries" xlfile = r"C:\MNaveed\DataScience\Python Practice New\SQL Queries\Open_Case_Data.xlsx" cnxn = pypyodbc.connect('Driver={SQL Server};Server=MyServerName;Database=MyDatabaseName;Trusted_Connection=Yes') cursor = cnxn.cursor() # Create a Pandas Excel writer using XlsxWriter as the engine outside the loop writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter') # File loop for subdir, dirs, files in os.walk(fpath): for file in files: filepath = os.path.join(subdir,file) if filepath.endswith(".txt"): if file != "ClosedAging_Cont.txt": txtdata = open(filepath, 'r') script = txtdata.read().strip() txtdata.close() cursor.execute(script) if file == "ClosedAging.txt": txtdata = open(os.path.join(subdir,"ClosedAging_Cont.txt"), 'r') script = txtdata.read().strip() txtdata.close() cursor.execute(script) col = [desc[0] for desc in cursor.description] data = cursor.fetchall() # Data frame from original question df = pd.DataFrame(list(data),columns=col) # Convert the dataframe to an XlsxWriter Excel object flnm = file.replace('.txt','').strip() df.to_excel(writer, sheet_name=flnm, index=False) print(file, " : Successfully Updated.") else: print(file, " : Ignoring this File") else: print(file, " : Ignoring this File") # Close the Pandas Excel writer and output the Excel file writer.save() ctypes.windll.user32.MessageBoxW(0,"Open Case Reporting Data Successfully Updated","Open Case Reporting",1)