一 excel表格自动将数据导入数据库,限制文件后缀名为.xlsx
文件1:
excelTodatabase.py
注意:每个sheet生成一张表,表名字为sheet的名字,自动将int类型和日期类型转成字符类型,数据库连接方式改成自己对应的数据库,我这里是postgresql
import xlrd
from datetime import datetime
from xlrd import xldate_as_tuple
#根据有多少个sheets去创建多少个表,path为excel表格的路径
def createtable(path):
# 读取excel
data = xlrd.open_workbook(path)
# 根据sheet索引获取sheet的内容
print("excel全部的sheet为:", data.sheet_names())
sheet_names = data.sheet_names()
table_one = data.sheet_by_index(0)
print("一个sheet的全部列名为", table_one.row_values(0))
conn = psycopg2.connect(database='test', user='postgres', password='root', host='localhost')
cur = conn.cursor()
for i in range(0, len(sheet_names)):
#当前sheet的名字
table_name = sheet_names[i]
# 当前的sheet
now_table = data.sheet_by_index(i)
# 获得当前sheet的列数就是 属性数
cols_num = now_table.ncols
# 获得当前表格的行数,就是有多少的数据量
rows_numn = now_table.nrows
# 获得当前的属性的数组,其实就是第一例的值
attrs = now_table.row_values(0)
#判断表格是否存在
cur.e