国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python實(shí)現(xiàn)excel轉(zhuǎn)sqlite的方法

2019-11-25 16:00:51
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(shí)例講述了Python實(shí)現(xiàn)excel轉(zhuǎn)sqlite的方法。分享給大家供大家參考,具體如下:

Python環(huán)境的安裝配置就不說(shuō)了,個(gè)人喜歡pydev的開發(fā)環(huán)境。

python解析excel需要使用第三方的庫(kù),這里選擇使用xlrd

先看excel內(nèi)容:

然后是生成的數(shù)據(jù)庫(kù):

下面是源代碼:

#!/usr/bin/python# encoding=utf-8'''''Created on 2013-4-2@author: ting'''from xlrd import open_workbookimport sqlite3import typesdef read_excel(sheet):  # 判斷有效sheet  if sheet.nrows > 0 and sheet.ncols > 0:    for row in range(1, sheet.nrows):      row_data = []      for col in range(sheet.ncols):        data = sheet.cell(row, col).value        # excel表格內(nèi)容數(shù)據(jù)類型轉(zhuǎn)換 float->int,unicode->utf-8        if type(data) is types.UnicodeType: data = data.encode("utf-8")        elif type(data) is types.FloatType: data = int(data)        row_data.append(data)      check_data_length(row_data)# 檢查row_data長(zhǎng)度def check_data_length(row_data):  if len(row_data) == 3:    insert_sqlite(row_data)def insert_sqlite(row_data):  # 打開數(shù)據(jù)庫(kù)(不存在時(shí)會(huì)創(chuàng)建數(shù)據(jù)庫(kù))  con = sqlite3.connect("test.db")  cur = con.cursor()  try:    cur.execute("create table if not exists contacts(_id integer primary key "/            "autoincrement,name text,age integer,number integer)")    # 插入數(shù)據(jù)不要使用拼接字符串的方式,容易收到sql注入攻擊    cur.execute("insert into contacts(name,age,number) values(?,?,?)", row_data)    con.commit()  except sqlite3.Error as e:    print "An error occurred: %s", e.args[0]  finally:    cur.close    con.closexls_file = "test.xls"book = open_workbook(xls_file)for sheet in book.sheets():  read_excel(sheet)print "------ Done ------"

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python常見數(shù)據(jù)庫(kù)操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 察雅县| 怀安县| 潢川县| 普定县| 洞口县| 崇义县| 石屏县| 斗六市| 岗巴县| 根河市| 禄劝| 威宁| 高雄市| 洛川县| 京山县| 南乐县| 祁阳县| 宿州市| 庆云县| 盐山县| 龙州县| 溧阳市| 汝阳县| 新闻| 额尔古纳市| 金堂县| 灵丘县| 新沂市| 垦利县| 平度市| 岳阳市| 鸡东县| 乾安县| 乌拉特中旗| 邵武市| 鄂伦春自治旗| 板桥市| 昭通市| 丹凤县| 成都市| 胶州市|