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