一、Excel模塊:xlrd(讀)、xlwt(寫)、xlutils(結合讀寫可修改excel)
1、從mysql中讀取數據
import xlrd,xlwt,xlutils import pymysql def sql_connect(sql): conn = pymysql.connect(host='127.0.0.1',port=3306, user='root', password='123456',db='sql_python',charset='utf8') cur = conn.cursor() cur.execute(sql) data = cur.fetchall() cur.close() conn.close() return data
2、從mysql中讀取數據寫入excel中
#寫數據 def write_excel(filename, data): book = xlwt.Workbook() #創建excel對象 sheet = book.add_sheet('sheet1') #添加一個表 c = 0 #保存當前列 for d in data: #取出data中的每一個元組存到表格的每一行 for index in range(len(d)): #將每一個元組中的每一個單元存到每一列 sheet.write(c,index,d[index]) c += 1 book.save(filename) #保存excel sql = 'select * from stu' res = sql_connect(sql) write_excel('firstsheet.xls', res)
3、從excel中讀取數據
#讀數據 def read_excel(filename): book = xlrd.open_workbook(filename) sheet = book.sheet_by_name('sheet1') rows = sheet.nrows #獲取行數 cols = sheet.ncols #獲取列數 for c in range(cols): #讀取每一列的數據 c_values = sheet.col_values(c) print(c_values) for r in range(rows): #讀取每一行的數據 r_values = sheet.row_values(r) print(r_values) print(sheet.cell(1,1)) #讀取指定單元格的數據 read_excel('firstsheet.xls')
4、從excel讀取數據寫入mysql
#從excel讀取數據寫入mysql def excel_to_mysql(filename): conn = pymysql.connect(host='127.0.0.1', port=3306, user='jessica', password='123456', db='sql_python',charset='utf8') cur = conn.cursor() #連接數據庫 book = xlrd.open_workbook(filename) sheet = book.sheet_by_name('sheet1') rows = sheet.nrows #獲取行數 for r in range(1,rows): #將標題之外的其他行寫入數據庫 r_values = sheet.row_values(r) sql = 'insert into stu2 values(%s,%s)' data = cur.execute(sql,r_values) #將每一行插入sql conn.commit() #插入所有數據后提交 cur.close() conn.close() excel_to_mysql('firstsheet.xls')
5、修改excel
from xlutils.copy import copy def modify_excel(filename): book = xlrd.open_workbook(filename) # 打開excel new_book = copy(book) # 復制excel sheet = new_book.get_sheet(0) # 獲取第一個表格的數據 sheet.write(0, 1, 'Haha') # 修改0行1列的數據為'Haha' new_book.save('secondsheet.xls') # 保存新的excel os.remove(filename) # 刪除舊的excel os.rename('secondsheet.xls', filename) # 將新excel重命名 modify_excel('firstsheet.xls')