Python實現(xiàn)將sqlite數(shù)據(jù)庫導出轉成Excel(xls)表的方法
本文實例講述了Python實現(xiàn)將sqlite數(shù)據(jù)庫導出轉成Excel(xls)表的方法。分享給大家供大家參考,具體如下:
1. 假設已經(jīng)安裝帶有sliqte 庫的Python環(huán)境
我的是Python2.5
2. 下載 python xls 寫操作包(xlwt)并安裝
下載地址: http://pypi.python.org/pypi/xlwt
3. 下面就是代碼(db2xls.py):
import sqlite3 as sqlite
from xlwt import *
#MASTER_COLS = ['rowid', 'type','name','tbl_name', 'rootpage','sql']
def sqlite_get_col_names(cur, table):
query = 'select * from %s' % table
cur.execute(query)
return [tuple[0] for tuple in cur.description]
def sqlite_query(cur, table, col = '*', where = ''):
if where != '':
query = 'select %s from %s where %s' % (col, table, where)
else:
query = 'select %s from %s ' % (col, table)
cur.execute(query)
return cur.fetchall()
def sqlite_to_workbook(cur, table, workbook):
ws = workbook.add_sheet(table)
print 'create table %s.' % table
for colx, heading in enumerate(sqlite_get_col_names(cur, table)):
ws.write(0,colx, heading)
for rowy,row in enumerate(sqlite_query(cur, table)):
for colx, text in enumerate(row):
ws.write(rowy+ 1, colx, text)
def main(dbpath):
xlspath = dbpath[0:dbpath.rfind('.')] + '.xls'
print "<%s> --> <%s>"% (dbpath, xlspath)
db = sqlite.connect(dbpath)
cur = db.cursor()
w = Workbook()
for tbl_name in [row[0] for row in sqlite_query(cur, 'sqlite_master', 'tbl_name', 'type = \'table\'')]:
sqlite_to_workbook(cur,tbl_name, w)
cur.close()
db.close()
if tbl_name !=[]: w.save(xlspath)
if __name__ == "__main__":
# arg == database path
main(sys.argv[1])
4. 用法:
> python <path>/db2xls.py dbpath
如果沒錯,會在數(shù)據(jù)庫的目錄下生成同名的xls文件
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python Tkinter Entry和Text的添加與使用詳解
這篇文章主要介紹了Python Tkinter Entry和Text的添加與使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
python實現(xiàn)簡單tftp(基于udp協(xié)議)
這篇文章主要為大家詳細介紹了python實現(xiàn)簡單tftp,基于udp協(xié)議,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
Python的Django框架中使用SQLAlchemy操作數(shù)據(jù)庫的教程
SQLAlchemy是Python一個專門的數(shù)據(jù)庫管理工具,如果對Django ORM覺得有些生疏的話完全可以結合SQLAlchemy,這里我們就來總結一下Python的Django框架中使用SQLAlchemy操作數(shù)據(jù)庫的教程2016-06-06
python實現(xiàn)n個數(shù)中選出m個數(shù)的方法
今天小編就為大家分享一篇python實現(xiàn)n個數(shù)中選出m個數(shù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11

