本文實(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ì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選