曾某年某一天某地
时间如静止的空气
你的不羁
给我惊喜
——《谁愿放手》陈慧琳
入职新公司两个多月,发现这边的数据基础很差,没有维度建模的数仓,很多数据甚至没有系统承载,大量的Excel表,大量的人工处理工作,现阶段被迫“面向Excel”编程。本文主要介绍使用Python读取Excel数据并导入数据库的方法,供各位小伙伴参考。
Python读取Esxcel数据主要是使用pandas包
(一)Excel表数据如下
(二)读取Excel相关代码如下,其中sheet_name可以省略,sheet_name="具体sheet页面"则只读该sheet页,sheet_name=0则读取第一个sheet页。
import pandas as pddf = pd.read_excel("test_20230312.xlsx", sheet_name="Sheet1")
print(df)
(三)结果展示
Python连接mysql数据库主要是使用pymysql包
(一)创建数据库连接,读表测试。
import pymysqlconn = pymysql.connect(host='localhost',port=3306,user='xxx',password='xxxxxx',database='test',charset='utf8')df = pd.read_sql('select * from test.dim_category', con=conn)
print(df)
(二)结果展示
(一)具体代码
import pandas as pd
import pymysqlconn = pymysql.connect(host='localhost',port=3306,user='xxx',password='xxxxxx',database='test',charset='utf8')df = pd.read_excel("test_20230312.xlsx", sheet_name="Sheet1")
infodata = pd.DataFrame(df).values
cur = conn.cursor()length = len(infodata)
for i in range(0, length):data_each = []data_each = infodata[i]print(data_each)sql = "insert into test_python_insert values{}".format(tuple(data_each))try:cur.execute(sql)conn.commit()print(i)except:conn.rollback()cur.close()
conn.close()
(一)结果展示
Python可以通过一些非常实用的包,如pandas,numpy等,对数据进行清洗,整理分析,合理利用Python可以提高我们处理分析数据的效率。