標籤:下標 student 文檔 exp pymysql work rate 匯出 自動
1)讀excel,使用xlrd模組
import xlrd
book =xlrd.open_workbook(‘app_student.xls‘)
sheet=book.sheet_by_index(0) #根據順序擷取的
# sheet2=book.sheet_by_name(‘sheet1‘) #也可根據名字擷取
# print(sheet.cell(0,0).value) #指定sheet頁裡面行和列擷取資料
# print(sheet.row_values(0)) #擷取到第幾行的內容
# print(sheet.nrows) #擷取到excel裡面總共有多少行
for i in range(sheet.nrows): #迴圈擷取到每行資料
print(sheet.row_values(i))
print(sheet.ncols) #總共多少列
2)修改excel,使用xrld模組
import xlrd
from xlutils import copy #匯入xlutils模組裡的copy方法
book=xlrd.open_workbook(‘app_student.xls‘) #先用xlrd模組,開啟一個excel
new_book=copy.copy(book) #通過xlutils這個模組裡面的copy方法,複製一份excel
sheet=new_book.get_sheet(0) #擷取sheet頁
lis=[‘編號‘,‘姓名‘,‘性別‘,‘年齡‘,‘地址‘,‘班級‘,‘手機號‘,‘金幣‘,]
col=0
for i in lis: #把list裡的值寫入excel的0行(從0開始計數)
sheet.write(0,col,i)
col +=1
new_book.save(‘app_student.xls‘) #再把新excel命名為之前文檔的名字
3)通用匯出excel,使用xlwt模組
import pymysql,xlwt
def export_excel(table_name):
host,user,passwd,db=‘xx.xx.xx.xx‘,‘aaa‘,‘123456‘,‘aaa‘ #pymysql的資訊
coon = pymysql.connect(
host=host, user=user, passwd=passwd,
port=3306, db=db, charset=‘utf8‘ # port必須寫int類型,charset必須寫utf8
)
cur = coon.cursor() # 建立遊標
sql=‘select * from %s;‘%table_name
cur.execute(sql) #執行sql語句
fileds=[filed[0] for filed in cur.description] #表頭所有的欄位
print(fileds)
all_data=cur.fetchall() #擷取資料返回的所有資料
book=xlwt.Workbook() #建立一個excel
sheet=book.add_sheet(‘sheet1‘) #新增一個sheet
for col,filed in enumerate(fileds): #把表頭欄位寫入sheet的0行
sheet.write(0,col,filed)
#print(all_data)
row=1 #定義一個變數,控制行
for data in all_data: #控制行
for col, filed in enumerate(data): #控制列,enumerate自動取下標,加1
sheet.write(row, col, filed) #行不變,變換列,依次寫入資料
row +=1 #向下移動行數
book.save(‘%s.xls‘%table_name) #儲存表格
export_excel(‘app_student‘) #匯出表格
新手學習python(十一)讀 / 修改 / 匯出excel