2017-03-21 15 views
0

複数のSQLクエリを実行できるPythonスクリプトを作成し、そのクエリの出力をExcelに保存します。 私は4つのSQLクエリ、すなわちScript1、Script2、Script3 & Script4があり、生成されたExcelブックをE:\ Testに保存したいとします。そのブックにはScript1出力が含まれています。に。私はクエリを書いていますが、そのスクリプトは1つだけです。このスクリプト私がテストした名前のExcelシートを生成することが可能ですが、私は残りのスクリプトを実行する方法、それらの出力は同じワークブックの他のシートに表示されるようにを使用することにより は Pythonを使用して別のシートにデータを抽出する

import psycopg2 
import sys 
import pprint 
import pandas as pd 
import os 
import openpyxl.cell 

COMMASPACE = ', ' 
def main(): 
    conn_string = "dbname='abc' user='qwerty' host='pqr' password='******' port='1234'" 

    script1 = """ 
select * From something1  
""" 
script2 = """ 
select * From something2  
""" 
script3 = """ 
    select * From something3  
    """ 
script4 = """ 
    select * From something4  
    """ 
    pprint.pprint ('Making connection to the Database...')  
    con1 = psycopg2.connect(conn_string) 
    cur = con1.cursor() 
    pprint.pprint ('Execution Start') 
    cur.execute(script) 
    if not cur.rowcount: 
     pprint.pprint ('Oops! Error Occured') 
    else: 
     columns = [desc[0] for desc in cur.description] 
     data = cur.fetchall() 
     df = pd.DataFrame(list(data), columns=columns) 
     df.columns = map(str.upper, df.columns) 
     writer = pd.ExcelWriter('E:\\Test.xlsx') 
     df.to_excel(writer, sheet_name='Sheet1') 
     def hide_column(ws, column_id): 
      if isinstance(column_id, int): 
       assert column_id >= 1, "Column numbers must be 1 or greater" 
       column_id = openpyxl.cell.get_column_letter(column_id) 
      column_dimension = ws.column_dimensions[column_id] 
      column_dimension.hidden = True 
     writer.save() 
    print ("END of extraction")  
if __name__ == "__main__": 
    main() 

答えて

0

がでread_sqlパンダを使用してみてくださいヘルプSqlの錬金術。

from openpyxl import load_workbook 
from sqlalchemy import create_engine 
import pandas as pd 

# Parameters for SQL Alchemy 
ServerName = "your_Server_Name" 
Database = "Your_Database" 
Driver = "Your_Driver" 

# Create the connection 
engine = create_engine('mssql+pyodbc://' + ServerName + '/' + Database + "?" + Driver) 

# reading in the dataframes 
df1 = pd.read_sql_query("select * from somewhere", engine) 
df2 = pd.read_sql_query("select * from somewhere_else", engine) 

# Using openpyxl to write to excel sheets 
file = 'Your_file_path_Here' 
book = load_workbook(file) 
writer = pd.ExcelWriter(file, engine='openpyxl') 
writer.book = book 

# now start writing them to sheets 
df1.to_excel(writer, index=None, sheet_name='SQL1') 
df1.to_excel(writer, index=None, sheet_name='SQL2') 
+0

こんにちはMattR、Redshiftデータベースを使用して、ユーザーとパスワードなしで接続していますか? 接続できません。 –

+0

@AquilAbbasについては、[このモジュール](https://pypi.python.org/pypi/sqlalchemy-redshift)を参照してください。確かに、私は以前に赤方偏移を使ったことはありません。しかし、コードがクラックするのが難しい場合は、レッドシフトでCSVファイルを作成し、パンダ内でそのように読むこともできます。 – MattR

+0

または[ここをクリック](http://docs.aws.amazon.com/redshift/latest/mgmt/install-odbc-driver-windows.html)を参照してください。または、SQL Alchemyをスキップし、[このリンク](https://blog.blendo.co/access-your-data-in-amazon-redshift-and-postgresql-with-python-and-r/)をチェックしてください。 – MattR

関連する問題