• <tfoot id="ukgsw"><input id="ukgsw"></input></tfoot>
    
    • 久久精品精选,精品九九视频,www久久只有这里有精品,亚洲熟女乱色综合一区
      分享

      python

       寧?kù)o致遠(yuǎn)oj1kn5 2019-05-12

      一   excel表格自動(dòng)將數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫(kù),限制文件后綴名為.xlsx

      文件1:excelTodatabase.py
      注意:每個(gè)sheet生成一張表,表名字為sheet的名字,自動(dòng)將int類(lèi)型和日期類(lèi)型轉(zhuǎn)成字符類(lèi)型,數(shù)據(jù)庫(kù)連接方式改成自己對(duì)應(yīng)的數(shù)據(jù)庫(kù),我這里是postgresql
      1. import xlrd
      2. from datetime import datetime
      3. from xlrd import xldate_as_tuple
      4. #根據(jù)有多少個(gè)sheets去創(chuàng)建多少個(gè)表,path為excel表格的路徑
      5. def createtable(path):
      6. # 讀取excel
      7. data = xlrd.open_workbook(path)
      8. # 根據(jù)sheet索引獲取sheet的內(nèi)容
      9. print("excel全部的sheet為:", data.sheet_names())
      10. sheet_names = data.sheet_names()
      11. table_one = data.sheet_by_index(0)
      12. print("一個(gè)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. #當(dāng)前sheet的名字
      17. table_name = sheet_names[i]
      18. # 當(dāng)前的sheet
      19. now_table = data.sheet_by_index(i)
      20. # 獲得當(dāng)前sheet的列數(shù)就是 屬性數(shù)
      21. cols_num = now_table.ncols
      22. # 獲得當(dāng)前表格的行數(shù),就是有多少的數(shù)據(jù)量
      23. rows_numn = now_table.nrows
      24. # 獲得當(dāng)前的屬性的數(shù)組,其實(shí)就是第一例的值
      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('存在了,直接將表的內(nèi)容插入')
      32. # 將當(dāng)前的sheet插入到數(shù)據(jù)庫(kù)
      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. # 處理要插入的數(shù)據(jù),把非字符串的數(shù)據(jù)轉(zhuǎn)換成字符串類(lèi)型,同事將字符串變成 sql語(yǔ)句需要的類(lèi)型
      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進(jìn)行建表,
      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. # 將當(dāng)前的sheet插入到數(shù)據(jù)庫(kù)
      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. # 處理要插入的數(shù)據(jù),把非字符串的數(shù)據(jù)轉(zhuǎn)換成字符串類(lèi)型,同事將字符串變成 sql語(yǔ)句需要的類(lèi)型
      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()

      二   數(shù)據(jù)庫(kù)信息導(dǎo)出到excel表格,生成 .xls格式的表格(.xlsx格式打不開(kāi))

      文件1 dbToExcel.py  

      注意:修改對(duì)應(yīng)數(shù)據(jù)庫(kù)的連接方式,我這里是postgresql,返回結(jié)果"ok"代表成功

      1. import xlwt
      2. import psycopg2
      3. import os
      4. import datetime
      5. def tableExportToXlsx(sql):#sql 為數(shù)據(jù)庫(kù)查詢(xún)語(yǔ)句,將會(huì)把查詢(xún)的數(shù)據(jù)導(dǎo)出
      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. #重置游標(biāo)位置
      11. cur.scroll(0,mode='absolute')
      12. #搜取所有的結(jié)果
      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. #寫(xiě)入表格的屬性值
      19. for i in range(0,len(attrs)):
      20. sheet.write(0,i,attrs[i][0])
      21. print('表格屬性:',attrs[i][0])
      22. #將數(shù)據(jù)庫(kù)的數(shù)據(jù)導(dǎo)入表格
      23. row = 1
      24. col = 0
      25. for row in range(1,len(results)+1):
      26. print('寫(xiě)',row,'行數(shù)據(jù)')
      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("現(xiàn)在的目錄是" + 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('數(shù)據(jù)庫(kù)中成功導(dǎo)出數(shù)據(jù)')
      41. return {'path':file_path,'name':file_name}
      42. else:
      43. print('數(shù)據(jù)庫(kù)導(dǎo)出錯(cuò)誤')
      44. return 'error'



        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶(hù)發(fā)布,不代表本站觀(guān)點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶(hù) 評(píng)論公約

        類(lèi)似文章 更多

        主站蜘蛛池模板: 亚洲AV无码精品色午夜果冻| 国产精品VA尤物在线观看| 夜鲁夜鲁很鲁在线视频 视频| 无码精品国产VA在线观看DVD | 好男人好资源WWW社区| 中文无码久久精品| 国产精品无码a∨麻豆| 欧美午夜成人片在线观看| 人妻在卧室被老板疯狂进入| 草裙社区精品视频播放| 国产特级毛片AAAAAA视频| 国产福利深夜在线观看| 欧美国产日韩在线三区| 日韩有码av中文字幕| JAPANESE国产在线观看播放| 国产午夜福利精品视频| 日产无人区一线二线三线乱码蘑菇| 偷拍专区一区二区三区| 日产高清砖码砖专区| 久久香蕉国产线看观看怡红院妓院| 亚洲AV永久纯肉无码精品动漫 | 亚洲欧美偷国产日韩| 呦系列视频一区二区三区| 韩国精品久久久久久无码| 国自产偷精品不卡在线| 久久亚洲道色宗和久久| 国产中文字幕精品在线| AAA级久久久精品无码片| 亚洲国产精品久久久天堂麻豆宅男| 欧洲国产精品无码专区影院| 成 人色 网 站 欧美大片| 少妇无套内谢免费视频| 久久婷婷国产剧情内射白浆| 免费国产VA在线观看视频| 亚洲国产中文字幕精品| 精品久久人人妻人人做精品| 99RE6热在线精品视频观看| 国产亚洲精品午夜福利| 伊人久久大香线蕉亚洲五月天 | 国产精品久久毛片| 国产亚洲欧美另类一区二区 |