一 excel表格自动将数据导入数据库,限制文件后缀名为.xlsx文件1:excelTodatabase.py
注意:每个sheet生成一张表,表名字为sheet的名字,自动将int类型和日期类型转成字符类型,数据库连接方式改成自己对应的数据库,我这里是postgresql
from datetime import datetime from xlrd import xldate_as_tuple #根据有多少个sheets去创建多少个表,path为excel表格的路径 data = xlrd.open_workbook(path) 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') for i in range(0, len(sheet_names)): table_name = sheet_names[i] now_table = data.sheet_by_index(i) cols_num = now_table.ncols rows_numn = now_table.nrows attrs = now_table.row_values(0) cur.execute("SELECT to_regclass('%s') is not null" % table_name) for k in range(1, rows_numn): row_vlaue = now_table.row_values(k) # 处理要插入的数据,把非字符串的数据转换成字符串类型,同事将字符串变成 sql语句需要的类型 for a in range(0, len(row_vlaue)): ctype = now_table.cell(k, a).ctype #ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error if ctype ==2 and row_vlaue[a] % 1 ==0 : d = datetime(*xldate_as_tuple(row_vlaue[a],0)) row_vlaue[a] = d.strftime('%Y-%m-%d') row_vlaue[a] = "'" + c + "'" print(','.join(row_vlaue)) sql = "INSERT INTO %s(%s) VALUES(%s)" % (table_name, ','.join(attrs), ','.join(row_vlaue)) cur.execute("CREATE TABLE " + table_name + "();") cur.execute("ALTER TABLE %s ADD COLUMN id SERIAL primary key ;" % table_name) # cur.execute("CREATE SEQUENCE users_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1;" ) cur.execute("alter table %s alter column id set default nextval('users_id_seq'); " % table_name) for j in range(0, cols_num): cur.execute("ALTER TABLE %s ADD COLUMN %s VARCHAR(200);" % (table_name, attrs[j])) for k in range(1, rows_numn): row_vlaue = now_table.row_values(k) # 处理要插入的数据,把非字符串的数据转换成字符串类型,同事将字符串变成 sql语句需要的类型 for a in range(0, len(row_vlaue)): ctype = now_table.cell(k, a).ctype # ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error if ctype == 2 and row_vlaue[a] % 1 == 0: d = datetime(*xldate_as_tuple(row_vlaue[a], 0)) row_vlaue[a] = d.strftime('%Y-%m-%d') row_vlaue[a] = "'" + c + "'" print(','.join(row_vlaue)) sql = "INSERT INTO %s(%s) VALUES(%s)" % (table_name, ','.join(attrs), ','.join(row_vlaue))
二 数据库信息导出到excel表格,生成 .xls格式的表格(.xlsx格式打不开)文件1 dbToExcel.py
注意:修改对应数据库的连接方式,我这里是postgresql,返回结果"ok"代表成功 def tableExportToXlsx(sql):#sql 为数据库查询语句,将会把查询的数据导出 conn = psycopg2.connect(database='test',user='postgres',password='root',host='localhost') cur.scroll(0,mode='absolute') workbook = xlwt.Workbook() sheet = workbook.add_sheet(table_name,cell_overwrite_ok=True) for i in range(0,len(attrs)): sheet.write(0,i,attrs[i][0]) print('表格属性:',attrs[i][0]) for row in range(1,len(results)+1): for col in range(0,len(attrs)): sheet.write(row,col,results[row-1][col]) print(results[row-1][col]) nowpath = os.path.dirname(__file__) print("现在的目录是" + nowpath) act_path = os.path.dirname(nowpath) app_path = os.path.dirname(act_path) file_path = app_path + '\\xlsx_tmp' export_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S') file_name = 'act-{0}.xls'.format(export_time) print('文件路径为' +os.path.join(file_path,file_name)) workbook.save(os.path.join(file_path,file_name)) if os.path.isfile(os.path.join(file_path,file_name)): return {'path':file_path,'name':file_name}
|