473,386 Members | 1,654 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Update SQL output data into Existing Excel in respective sheet

Hi All,

My Name Is Mohammad Naveed and this is my First post.

i am new to Python programming and seeking for some help/guidance in correcting my python code.

Here my query is.
1. I have one Excel file which has (7 Tabs).
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.

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. 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 file and updating only current output data into excel file.

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).
Aug 13 '17 #1
3 2303
here is my code

Expand|Select|Wrap|Line Numbers
  1. import pypyodbc
  2. import pandas as pd
  3. import os
  4. import ctypes
  5. from pandas import ExcelWriter
  6. fpath = r"C:\MNaveed\DataScience\Python Practice New\SQL Queries"
  7. xlfile = r"C:\MNaveed\DataScience\Python Practice New\SQL Queries\Open_Case_Data.xlsx"
  8. cnxn = pypyodbc.connect('Driver={SQL Server};Server=MyServerName;Database=MyDatabaseName;Trusted_Connection=Yes')
  9. cursor = cnxn.cursor()
  10.  
  11. for subdir, dirs, files in os.walk(fpath):
  12.     for file in files:
  13.         #print(os.path.join(subdir,file))
  14.         filepath = os.path.join(subdir,file)
  15.         #print("FilePath: ", filepath)
  16.  
  17.         if filepath.endswith(".txt"):
  18.             if file != "ClosedAging_Cont.txt":
  19.                 txtdata = open(filepath, 'r')
  20.                 script = txtdata.read().strip()
  21.                 txtdata.close()
  22.                 cursor.execute(script)
  23.                 if file == "ClosedAging.txt":
  24.                     txtdata = open(os.path.join(subdir,"ClosedAging_Cont.txt"), 'r')
  25.                     script = txtdata.read().strip()
  26.                     txtdata.close()
  27.                     cursor.execute(script)
  28.  
  29.                 col = [desc[0] for desc in cursor.description]
  30.                 data = cursor.fetchall()
  31.                 df = pd.DataFrame(list(data),columns=col)
  32.  
  33.                 #save_xls(df,xlfile)
  34.  
  35.                 writer = pd.ExcelWriter(xlfile)
  36.                 flnm = file.replace('.txt','').strip()
  37.                 df.to_excel(writer,sheet_name=flnm,index=False)
  38.                 writer.save()
  39.  
  40.                 print(file, " : Successfully Updated.")
  41.             else:
  42.                 print(file, " : Ignoring this File")
  43.         else:
  44.             print(file, " : Ignoring this File")
  45.  
  46. ctypes.windll.user32.MessageBoxW(0,"Open Case Reporting Data Successfully Updated","Open Case Reporting",1)
  47.  
Aug 13 '17 #2
Anyone can help me out with this query...
Aug 13 '17 #3
Hi All,

anyone can help me out with this query..
Aug 14 '17 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Ajay Tiku | last post by:
Hi every one, I am trying to build an applicatiuon which is supposed to read some data from excel spread sheet. can some one please help me in showing how. The excel file is created by other...
1
by: Steven Stewart | last post by:
I have a user who has been using Excel for a while to keep statistics and print reports. She finds using it cumbersome because of long formulas and a lot of copying and pasting. I have designed...
4
by: Marco Aschwanden | last post by:
Hi I would like to 1. import an existing Excel-sheet (a template) 2. and add some data to it 3. and save it under a different name afterwards. To me it seems, that pyExcelerator does not...
7
by: Vanessa | last post by:
hi Everyone, I have two questions on exporting data to Excel using ASP (w/o converting formatted excel file into web page and then plug in the dynamic data): 1. Can we export data into...
5
by: hmiller | last post by:
Hey there folks: I have been trying to get this work for about a week now. I'm new to VBA... I am trying to transfer a populated table in Access to an existing, but blank, Excel worksheet. I...
1
by: roger.rigsby | last post by:
Ok I know how to get the data I want from mysql but I need to actually do something with this data and then send it back to mySQL. Company heads love the spreadsheet view so this is serious...
7
Merlin1857
by: Merlin1857 | last post by:
Its great producing data for users to look at in your web pages and generally that is sufficient for their needs but sometimes you may want to supply your user with the data in a form they can...
2
by: ram712 | last post by:
i need to create/add a copy of an excel sheet to an existing excel sheet consisting of table data so that the new excel sheet renamed automatically. also, the new excel sheet should be blank but...
0
by: Tahir Mehmood | last post by:
Hi, Thanks in advance. I am facing problem regading adding and deleting records from acess 2007 database to excel 2007 sheet.Sheet exists on system and saved at specific path.Plz help me i am in...
1
by: Mark Chemali | last post by:
How can I export a DataGrid in ASP.NET to an existing Excel Workbook and place the gridview data in the first sheet? Existing Excel workbook is found on c:/Project/Inm.xls Below is my code to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.