python 學習(三)資料庫、EXCEL處理
阿新 • • 發佈:2020-07-15
1.python自帶資料庫,此處使用MYSQL資料庫,編寫資料庫類做資料庫處理,編寫excel 類處理excel的讀寫,下面程式碼可以實現從excel讀取資料寫入資料庫,從資料庫讀取資料寫入excel:
import xlrd,xlwt import pymysql class Mysql: def __init__(self): self.content = pymysql.Connect( host='192.168.207.63', # mysql的主機ip port=32774, # 埠 user='root', # 使用者名稱 passwd='123456', # 資料庫密碼 db='test', # 資料庫名 charset='utf8', # 字符集 ) self.cursor = self.content.cursor() def query(self): sql = "select grade,teacher,location from grade;" self.cursor.execute(sql)for row in self.cursor.fetchall(): print("grade:%s\t teacher:%s\t location:%s" % row) rows.append(row) print(f"一共查詢到:{self.cursor.rowcount}") def readtable(self): sql = """select * from stu;""" self.cursor.execute(sql) rows= [] for row in self.cursor.fetchall(): print(row) rows.append(row) print(f"一共查詢到:{self.cursor.rowcount}") return rows def insert(self,grade,teacher,location): sql = """INSERT INTO grade(grade,teacher,location) VALUES(%s,%s,%s)""" values=(int(grade),str(teacher),str(location)) try: self.cursor.execute(sql,values) self.content.commit() # print("插入成功") except: self.content.rollback # print("插入失敗") def end(self): self.cursor.close() self.content.close() class Exceltable: def __init__(self): self.book = xlrd.open_workbook("grade.xls") #檔名,把檔案與py檔案放在同一目錄下 self.sheet = self.book.sheet_by_name("Sheet1") #execl裡面的worksheet1 def readrow(self,row): #ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error row_values = [] for i in range(self.sheet.ncols): cell=self.sheet.cell_value(row,i) ctype = self.sheet.cell(row,i).ctype if ctype == 2 and cell%1== 0: cell =int(cell) elif ctype == 3: # 轉成datetime物件 date = datetime(*xldate_as_tuple(cell, 0)) cell = date.strftime('%Y/%d/%m %H:%M:%S') elif ctype == 4: cell = True if cell == 1 else False row_values.append(cell) return row_values def readall(self): #ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error all_content = [] for i in range(1,self.sheet.nrows): row_values = [] for j in range(self.sheet.ncols): cell=self.sheet.cell_value(i,j) ctype = self.sheet.cell(i,j).ctype if ctype == 2 and cell%1== 0: cell =int(cell) elif ctype == 3: # 轉成datetime物件 date = datetime(*xldate_as_tuple(cell, 0)) cell = date.strftime('%Y/%d/%m %H:%M:%S') elif ctype == 4: cell = True if cell == 1 else False row_values.append(cell) all_content.append(row_values) return all_content def readmutirow(self,start,end): muti_content = [] for i in range(start,end+1): row_values = [] for j in range(self.sheet.ncols): cell=self.sheet.cell_value(i,j) ctype = self.sheet.cell(i,j).ctype if ctype == 2 and cell%1== 0: cell =int(cell) elif ctype == 3: # 轉成datetime物件 date = datetime(*xldate_as_tuple(cell, 0)) cell = date.strftime('%Y/%d/%m %H:%M:%S') elif ctype == 4: cell = True if cell == 1 else False row_values.append(cell) muti_content.append(row_values) return muti_content def writrow(self,rows): # 建立Excel工作薄 myWorkbook = xlwt.Workbook() # 3. 新增Excel工作表 mySheet = myWorkbook.add_sheet('test') # 4. 寫入資料 #myStyle = xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00') #資料格式 for i in range(len(rows)): for j in range(len(rows[i])): mySheet.write(i, j, rows[i][j]) #寫入A3,數值等於1 #5. 儲存 myWorkbook.save('Wtest.xls') if __name__ == '__main__': mysql = Mysql() myexcel=Exceltable() #讀單行 #cells=myexcel.readrow(3) #print(cells) #讀整個表 #all_content = myexcel.readall() #for cells in all_content: # print(cells) # mysql.insert(cells[0],cells[1],cells[2]) #讀指定表 #muti_content=myexcel.readmutirow(1,3) #for cells in muti_content: # print(cells) # mysql.insert(cells[0],cells[1],cells[2]) #查詢資料庫 #mysql.query() #將資料庫內容寫入EXCEL rows=mysql.readtable() myexcel.writrow(rows) mysql.end()
上面程式存在缺陷:1.處理資料量小,不適合大量資料處理,2.使用xlwt庫寫excel只支援.xls且僅支援新建,後續學習PANDAS後補充此章內容