這節說下如何用python把數據庫里的數據導出到excel里,並如何讀取excel, 修必excel等操作。
一、用python把數據庫里的數據導出到excel里
1、導入如下的模塊,沒有的話需要安裝
import pymysql #mysql連接模塊
import xlwt #寫excel的第三方庫
從數據庫導數據,寫到excel文件里
import pymysql,xlwt
def export_excel(table_name):
import pymysql
host, user, passwd, db = '127.0.0.1', 'xxx', '123456', 'xxxx'
conn = pymysql.connect(user=user,host=host,port=3306,passwd=passwd,db=db,charset='utf8')
cur = conn.cursor() # 建立游標
sql = 'select * from %s;' %table_name
cur.execute(sql) # 執行mysql
fileds = [filed[0] for filed in cur.description] # 列表生成式,所有字段
all_data = cur.fetchall() #所有數據
#寫excel
book = xlwt.Workbook() #先創建一個book
sheet = book.add_sheet('sheet1') #創建一個sheet表
# col = 0
# for field in fileds: #寫表頭的
# sheet.write(0, col, field)
# col += 1
#enumerate自動計算下標
for col, field in enumerate(fileds): #跟上面的代碼功能一樣
sheet.write(0, col, field)
#從第一行開始寫
row = 1 #行數
for data in all_data: #二維數據,有多少條數據,控制行數
for col, field in enumerate(data): #控制列數
sheet.write(row, col, field)
row += 1 #每次寫完一行,行數加1
book.save('%s.xls' %table_name) #保存excel文件
export_excel('app_student')
結果,生成了app_student.xls文件
二、內置函數enumerate
# enumerate #自動計算下標
# fileds = ['id', 'name', 'sex', 'addr', 'gold','score']
# for index, filed in enumerate(fileds): #同時打印下標
# print(index, filed)
三、讀excel
四、修改excel
import xlrd
from xlutils import copy #這個模塊需要這樣導入
五、操作數據庫,excel操作小結
cur = coon.cursor(cursor=pymysql.cursors.DictCursor)
建立游標的時候指定了游標類型,返回的就是一個字典了。
fetchall() #獲取到這個sql執行的全部結果,它把數據庫表里面的每一行數據放到一個list里面
[ ['1','2','3'] ] [{},{},{}]
fetchone() #獲取到這個sql執行的一條結果,它返回就只是一條數據
如果sql語句執行的結果是多條數據的時候,那就用fetchall()
如果你能確定sql執行的結果就只有一條,那么就用fetchone()
需求:只要你傳入一個表名,就能把所有的數據導入出來,字段名是excel的表頭
1、要動態獲取到表的字段 cur.description能獲取到表的字段
fileds = [ filed[0] for filed in cur.description ]
2、獲取數據了 select * from "%s" % table_name
3、循環寫入excel
enumerate([list,list2]) #循環的時候,直接獲取到下標,和值
for index,value in enumerate([list,list2]):
print(index,vlaue)