简体   繁体   English

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

[英]Update SQL output data into Existing Excel in respective sheet using python

I am new to Python programming and seeking for some help/guidance in correcting my python code.我是 Python 编程的新手,正在寻求一些帮助/指导来纠正我的 Python 代码。

Here my query is.这是我的查询。

  1. I have one Excel file which has (7 Tabs).我有一个 Excel 文件,其中包含(7 个选项卡)。
  2. I have one Folder which contains 7 different text file and each text file contains respective Tab SQL Query and each text file name is same as the Tab Name which is available in Excel File.我有一个包含 7 个不同文本文件的文件夹,每个文本文件包含各自的 Tab SQL 查询,每个文本文件名与 Excel 文件中可用的 Tab 名称相同。

I have a written a Python code to loop through all the text file one by one and execute that each text file SQL query and whatever data will come in output that output data should dump into existing excel file in that respective sheet/tab.我编写了一个 Python 代码来一个接一个地遍历所有文本文件,并执行每个文本文件 SQL 查询以及输出中将出现的任何数据,输出数据应转储到相应工作表/选项卡中的现有 excel 文件中。 i am using pandas to do this, however, code is working fine but while updating data into excel pandas is removing all existing sheets from the file and updating only current output data into excel file.我正在使用 Pandas 来执行此操作,但是,代码工作正常,但是在将数据更新到 excel 时,pandas 正在从文件中删除所有现有工作表,并仅将当前输出数据更新到 excel 文件中。

Example: if Python code execute a text file(Filename: Data) and after executing this SQL query we got some data and this data should dump into excel file (sheetname: Data).示例:如果 Python 代码执行一个文本文件(文件名:数据)并且在执行此 SQL 查询后我们得到了一些数据,这些数据应该转储到 excel 文件中(表名:数据)。

<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>

By looping through the text files, you overwrite the Excel file inside the loop each time.通过循环遍历文本文件,您每次都会覆盖循环内的 Excel 文件。 Instead instantiate pd.ExcelWriter(xlfile) and call writer.save() outside the loop.而是实例化 pd.ExcelWriter(xlfile) 并在循环外调用 writer.save() 。

The following example is adapted from the xlswriter documentation以下示例改编自xlswriter 文档

You can find more information about multiple sheets here: xlswriter documentaion - multiple sheets您可以在此处找到有关多张纸的更多信息: 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()

The following code addresses the concrete question but is untested.以下代码解决了具体问题,但未经测试。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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