操作excel(讀excel、修改excel)
練習
需求:只要你傳入一個表名,就能把所有的數據導入出來,字段名是excel的表頭
1、要動態獲取到表的字段 cur.description能獲取到表的字段
fileds = [ filed[0] for filed in cur.description ]
2、獲取數據了 select * from "%s" % table_name
3、循環寫入excel
import pymysql,xlwt
def export_excel(table_name):
host, user, passwd, db = ‘11XXX‘, ‘jxz‘, ‘123456‘, ‘jxz‘
coon = pymysql.connect(user=user, host=host, port=3306, passwd=passwd, db=db, charset=‘utf8‘)
cur = coon.cursor() # 建立遊標,指定cursor類型返回的是字典
sql = ‘select * from %s ;‘%table_name
cur.execute(sql) # 執行sql
fileds = [filed[0] for filed in cur.description] #所有的字段
all_data = cur.fetchall()
book = xlwt.Workbook()
sheet = book.add_sheet(‘sheet1‘)
for col,filed in enumerate(fileds): ######寫表頭的enumerate()獲取位置和值,自動計算下標,fileds = [‘id‘,‘name‘,‘sex‘,‘addr‘,‘gold‘,‘score‘]
for index,filed in enumerate(fileds):
print(index,filed)####
sheet.write(0,col,filed)
row = 1 #行數
for data in all_data: #行
for col, filed in enumerate(data): # 控制列
sheet.write(row, col, filed)
row+=1#每次寫完一行,行就加1
book.save(‘%s.xls‘%table_name)
export_excel(‘app_student‘)
**
enumerate([list,list2]) #循環的時候,直接獲取到下標,和值 二維數組
for index,value in enumerate([list,list2]):
print(index,vlaue)
###讀excel
import xlrd # xlrd讀excel模塊
book = xlrd.open_workbook(‘app_student.xls‘)
sheet = book.sheet_by_index(0) #獲取第一個sheet中的內容
# sheet2 = book.sheet_by_name(‘shee1‘) 也可以通過名字獲取
# print(sheet.cell(0,0).value) #指定sheet頁裏面行和lie獲取數據
# print(sheet.cell(1,0).value) #指定sheet頁裏面行和lie獲取數據
# print(sheet.row_values(0)) #這個獲取到第幾行的內容
# print(sheet.row_values(1)) #這個獲取到第幾行的內容
# print(sheet.nrows) #獲取到excel裏面總共有多少行 條數
# for i in range(sheet.nrows): #循環獲取到每行數據
# print(sheet.row_values(i))
print(sheet.ncols) #總共多少列
print(sheet.col_values(0)) #取第幾列的數據
###修改excel
指定安裝 python3 –m pip XXX
如果你電腦裏面裝了多個版本的python
python3 -m pip instatll xlutils
python2 -m pip instatll xlutils
import xlrd
from xlutils import copy #修改excel 模塊 此方法比較特殊
book = xlrd.open_workbook(‘app_student.xls‘)
#先用xlrd模塊,打開一個excel
new_book = copy.copy(book) #修改先要copy
#通過xlutils這個模塊裏面copy方法,復制一份excel
sheet = new_book.get_sheet(0) #獲取sheet頁 這是xlutils的方法
lis = [‘編號‘,‘名字‘,‘性別‘,‘年齡‘,‘地址‘,‘班級‘,‘手機號‘,‘金幣‘]
for col,filed in enumerate(lis):
sheet.write(0,col,filed)
new_book.save(‘app_student.xls‘)
操作excel(讀excel、修改excel)