Python實現(xiàn)excel轉(zhuǎn)sqlite的方法
本文實例講述了Python實現(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ù)庫(不存在時會創(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īng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
- Python讀取excel指定列生成指定sql腳本的方法
- Python3讀取Excel數(shù)據(jù)存入MySQL的方法
- python3+mysql查詢數(shù)據(jù)并通過郵件群發(fā)excel附件
- Python使用SQLite和Excel操作進行數(shù)據(jù)分析
- python實現(xiàn)讀取excel寫入mysql的小工具詳解
- Python實現(xiàn)讀寫sqlite3數(shù)據(jù)庫并將統(tǒng)計數(shù)據(jù)寫入Excel的方法示例
- Python實現(xiàn)將sqlite數(shù)據(jù)庫導出轉(zhuǎn)成Excel(xls)表的方法
- python 讀取excel文件生成sql文件實例詳解
- Python解析excel文件存入sqlite數(shù)據(jù)庫的方法
- 利用python在excel里面直接使用sql函數(shù)的方法
相關(guān)文章
python每次處理固定個數(shù)的字符的方法總結(jié)
使用python每次處理固定個數(shù)的字符,很多情況下都會遇到。本文對可能的方法做下總結(jié),供各位朋友學習參考2013-01-01
python筆記_將循環(huán)內(nèi)容在一行輸出的方法
今天小編就為大家分享一篇python筆記_將循環(huán)內(nèi)容在一行輸出的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Pyramid將models.py文件的內(nèi)容分布到多個文件的方法
默認的Pyramid代碼結(jié)構(gòu)中,就只有一個models.py文件,在實際項目中,如果需要對models進行分類,放到不同文件下,應(yīng)該怎么辦2013-11-11
詳解Python中sorted()和sort()的使用與區(qū)別
眾所周知,在Python中常用的排序函數(shù)為sorted()和sort()。本文將詳細介紹sorted()和sort()方法的代碼示例,并解釋兩者之間的區(qū)別,感興趣的可以了解一下2022-03-03

