Python實(shí)現(xiàn)excel轉(zhuǎn)sqlite的方法
本文實(shí)例講述了Python實(shí)現(xiàn)excel轉(zhuǎn)sqlite的方法。分享給大家供大家參考,具體如下:
Python環(huán)境的安裝配置就不說了,個人喜歡pydev的開發(fā)環(huán)境。
python解析excel需要使用第三方的庫,這里選擇使用xlrd
先看excel內(nèi)容:
然后是生成的數(shù)據(jù)庫:
下面是源代碼:
#!/usr/bin/python # encoding=utf-8 ''''' Created on 2013-4-2 @author: ting ''' from xlrd import open_workbook import sqlite3 import types def 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長度 def check_data_length(row_data): if len(row_data) == 3: insert_sqlite(row_data) def insert_sqlite(row_data): # 打開數(shù)據(jù)庫(不存在時(shí)會創(chuàng)建數(shù)據(jù)庫) 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.close xls_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ù)庫操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
- Python讀取excel指定列生成指定sql腳本的方法
- Python3讀取Excel數(shù)據(jù)存入MySQL的方法
- python3+mysql查詢數(shù)據(jù)并通過郵件群發(fā)excel附件
- Python使用SQLite和Excel操作進(jìn)行數(shù)據(jù)分析
- python實(shí)現(xiàn)讀取excel寫入mysql的小工具詳解
- Python實(shí)現(xiàn)讀寫sqlite3數(shù)據(jù)庫并將統(tǒng)計(jì)數(shù)據(jù)寫入Excel的方法示例
- Python實(shí)現(xiàn)將sqlite數(shù)據(jù)庫導(dǎo)出轉(zhuǎn)成Excel(xls)表的方法
- python 讀取excel文件生成sql文件實(shí)例詳解
- Python解析excel文件存入sqlite數(shù)據(jù)庫的方法
- 利用python在excel里面直接使用sql函數(shù)的方法
相關(guān)文章
Python實(shí)現(xiàn) 版本號對比功能的實(shí)例代碼
這篇文章主要介紹了 Python實(shí)現(xiàn) 版本號對比功能的實(shí)例代碼,文末給大家補(bǔ)充介紹了python 比較兩個版本號大小 ,需要的朋友可以參考下2019-04-04Pandas之drop_duplicates:去除重復(fù)項(xiàng)方法
下面小編就為大家分享一篇Pandas之drop_duplicates:去除重復(fù)項(xiàng)方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04python用pyinstaller封裝exe雙擊后瘋狂閃退解決辦法
本文主要介紹了python用pyinstaller封裝exe雙擊后瘋狂閃退解決辦法,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11PyQt5 QSerialPort子線程操作的實(shí)現(xiàn)
這篇文章主要介紹了PyQt5 QSerialPort子線程操作的實(shí)現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04