第九课: - 导出到CSV / EXCEL / TXT
第 9 课
将数据从microdost sql数据库导出到cvs,excel和txt文件。
In [1]:
# Import libraries
import pandas as pd
import sys
from sqlalchemy import create_engine, MetaData, Table, select
In [2]:
print('Python version ' + sys.version)
print('Pandas version ' + pd.__version__)
In [3]:
# Parameters
TableName = "data"
DB = {
'drivername': 'mssql+pyodbc',
'servername': 'DAVID-THINK',
#'port': '5432',
#'username': 'lynn',
#'password': '',
'database': 'BizIntel',
'driver': 'SQL Server Native Client 11.0',
'trusted_connection': 'yes',
'legacy_schema_aliasing': False
}
# Create the connection
engine = create_engine(DB['drivername'] + '://' + DB['servername'] + '/' + DB['database'] + '?' + 'driver=' + DB['driver'] + ';' + 'trusted_connection=' + DB['trusted_connection'], legacy_schema_aliasing=DB['legacy_schema_aliasing'])
conn = engine.connect()
# Required for querying tables
metadata = MetaData(conn)
# Table to query
tbl = Table(TableName, metadata, autoload=True, schema="dbo")
#tbl.create(checkfirst=True)
# Select all
sql = tbl.select()
# run sql code
result = conn.execute(sql)
# Insert to a dataframe
df = pd.DataFrame(data=list(result), columns=result.keys())
# Close connection
conn.close()
print('Done')
下面的所有文件将保存到当前的文件夹中。
导出到 CSV文件
In [4]:
df.to_csv('DimDate.csv', index=False)
print('Done')
导出到 EXCEL文件
In [5]:
df.to_excel('DimDate.xls', index=False)
print('Done')
导出到 TXT文件
In [6]:
df.to_csv('DimDate.txt', index=False)
print('Done')
This tutorial was rewrited by CDS