分享

python

 宁静致远oj1kn5 2019-05-12

一   excel表格自动将数据导入数据库,限制文件后缀名为.xlsx

文件1:excelTodatabase.py
注意:每个sheet生成一张表,表名字为sheet的名字,自动将int类型和日期类型转成字符类型,数据库连接方式改成自己对应的数据库,我这里是postgresql
  1. import xlrd
  2. from datetime import datetime
  3. from xlrd import xldate_as_tuple
  4. #根据有多少个sheets去创建多少个表,path为excel表格的路径
  5. def createtable(path):
  6. # 读取excel
  7. data = xlrd.open_workbook(path)
  8. # 根据sheet索引获取sheet的内容
  9. print("excel全部的sheet为:", data.sheet_names())
  10. sheet_names = data.sheet_names()
  11. table_one = data.sheet_by_index(0)
  12. print("一个sheet的全部列名为", table_one.row_values(0))
  13. conn = psycopg2.connect(database='test', user='postgres', password='root', host='localhost')
  14. cur = conn.cursor()
  15. for i in range(0, len(sheet_names)):
  16. #当前sheet的名字
  17. table_name = sheet_names[i]
  18. # 当前的sheet
  19. now_table = data.sheet_by_index(i)
  20. # 获得当前sheet的列数就是 属性数
  21. cols_num = now_table.ncols
  22. # 获得当前表格的行数,就是有多少的数据量
  23. rows_numn = now_table.nrows
  24. # 获得当前的属性的数组,其实就是第一例的值
  25. attrs = now_table.row_values(0)
  26. #判断表格是否存在
  27. cur.execute("SELECT to_regclass('%s') is not null" % table_name)
  28. flag = cur.fetchone()[0]
  29. print('flag',flag)
  30. if flag :
  31. print('存在了,直接将表的内容插入')
  32. # 将当前的sheet插入到数据库
  33. for k in range(1, rows_numn):
  34. row_vlaue = now_table.row_values(k)
  35. print(row_vlaue)
  36. print(','.join(attrs))
  37. # 处理要插入的数据,把非字符串的数据转换成字符串类型,同事将字符串变成 sql语句需要的类型
  38. for a in range(0, len(row_vlaue)):
  39. ctype = now_table.cell(k, a).ctype
  40. print('ctype', ctype)
  41. #ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
  42. if ctype ==2 and row_vlaue[a] % 1 ==0 :
  43. tmp = int(row_vlaue[a])
  44. row_vlaue[a] = str(tmp)
  45. if ctype == 3 :
  46. d = datetime(*xldate_as_tuple(row_vlaue[a],0))
  47. row_vlaue[a] = d.strftime('%Y-%m-%d')
  48. c = row_vlaue[a]
  49. row_vlaue[a] = "'" + c + "'"
  50. print(','.join(row_vlaue))
  51. sql = "INSERT INTO %s(%s) VALUES(%s)" % (table_name, ','.join(attrs), ','.join(row_vlaue))
  52. print(sql)
  53. cur.execute(sql)
  54. conn.commit()
  55. else:
  56. cur.execute("CREATE TABLE " + table_name + "();")
  57. conn.commit()
  58. # 为sheet进行建表,
  59. cur.execute("ALTER TABLE %s ADD COLUMN id SERIAL primary key ;" % table_name)
  60. conn.commit()
  61. # cur.execute("CREATE SEQUENCE users_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1;" )
  62. # conn.commit()
  63. cur.execute("alter table %s alter column id set default nextval('users_id_seq'); " % table_name)
  64. conn.commit()
  65. for j in range(0, cols_num):
  66. cur.execute("ALTER TABLE %s ADD COLUMN %s VARCHAR(200);" % (table_name, attrs[j]))
  67. conn.commit()
  68. # 将当前的sheet插入到数据库
  69. for k in range(1, rows_numn):
  70. row_vlaue = now_table.row_values(k)
  71. print(row_vlaue)
  72. print(','.join(attrs))
  73. # 处理要插入的数据,把非字符串的数据转换成字符串类型,同事将字符串变成 sql语句需要的类型
  74. for a in range(0, len(row_vlaue)):
  75. ctype = now_table.cell(k, a).ctype
  76. print('ctype', ctype)
  77. # ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
  78. if ctype == 2 and row_vlaue[a] % 1 == 0:
  79. tmp = int(row_vlaue[a])
  80. row_vlaue[a] = str(tmp)
  81. if ctype == 3:
  82. d = datetime(*xldate_as_tuple(row_vlaue[a], 0))
  83. row_vlaue[a] = d.strftime('%Y-%m-%d')
  84. c = row_vlaue[a]
  85. row_vlaue[a] = "'" + c + "'"
  86. print(','.join(row_vlaue))
  87. sql = "INSERT INTO %s(%s) VALUES(%s)" % (table_name, ','.join(attrs), ','.join(row_vlaue))
  88. print(sql)
  89. cur.execute(sql)
  90. conn.commit()
  91. conn.close()

二   数据库信息导出到excel表格,生成 .xls格式的表格(.xlsx格式打不开)

文件1 dbToExcel.py  

注意:修改对应数据库的连接方式,我这里是postgresql,返回结果"ok"代表成功

  1. import xlwt
  2. import psycopg2
  3. import os
  4. import datetime
  5. def tableExportToXlsx(sql):#sql 为数据库查询语句,将会把查询的数据导出
  6. table_name = "acts"
  7. conn = psycopg2.connect(database='test',user='postgres',password='root',host='localhost')
  8. cur = conn.cursor()
  9. cur.execute(sql)
  10. #重置游标位置
  11. cur.scroll(0,mode='absolute')
  12. #搜取所有的结果
  13. results = cur.fetchall()
  14. #获取属性名
  15. attrs = cur.description
  16. workbook = xlwt.Workbook()
  17. sheet = workbook.add_sheet(table_name,cell_overwrite_ok=True)
  18. #写入表格的属性值
  19. for i in range(0,len(attrs)):
  20. sheet.write(0,i,attrs[i][0])
  21. print('表格属性:',attrs[i][0])
  22. #将数据库的数据导入表格
  23. row = 1
  24. col = 0
  25. for row in range(1,len(results)+1):
  26. print('写',row,'行数据')
  27. for col in range(0,len(attrs)):
  28. sheet.write(row,col,results[row-1][col])
  29. print(results[row-1][col])
  30. nowpath = os.path.dirname(__file__)
  31. print("现在的目录是" + nowpath)
  32. act_path = os.path.dirname(nowpath)
  33. app_path = os.path.dirname(act_path)
  34. file_path = app_path + '\\xlsx_tmp'
  35. export_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
  36. file_name = 'act-{0}.xls'.format(export_time)
  37. print('文件路径为' +os.path.join(file_path,file_name))
  38. workbook.save(os.path.join(file_path,file_name))
  39. if os.path.isfile(os.path.join(file_path,file_name)):
  40. print('数据库中成功导出数据')
  41. return {'path':file_path,'name':file_name}
  42. else:
  43. print('数据库导出错误')
  44. return 'error'



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多