python操作excel表格(數據庫讀取)

今天學習了python操作excel表格,感覺很有意思,整理一下筆記

python讀取文件

讀取文件的方式1:直接讀取,最後需要close操作

def open_file2(file):
    f = open(file,"r")
    re = f.read()
    print(re)
    f.close()

def open_file3(file):
    try:
        f = open(file,"r")
        re = f.read()
        print(re)
    except:
        pass
    finally:
        f.close()

在讀取文件處理異常時,發現異常:

UnboundLocalError: local variable 'f' referenced before assignment
Traceback (most recent call last):
  File "/Users/apple/Downloads/11人臉識別/projects/PyDemo/excel/use_with.py", line 35, in <module>
    open_file_try()
  File "/Users/apple/Downloads/11人臉識別/projects/PyDemo/excel/use_with.py", line 26, in open_file_try
    f.close()
UnboundLocalError: local variable 'f' referenced before assignment

在處理異常時,更改了一下文件名看是否直接顯示except的內容,但是執行後發現抱了另一個錯,原因是在open文件時沒有找到文件,所以f相當於未定義,最後執行finally的內容的就找不到相應的f

讀取文件方式2:利用with讀取,最後不用進行close操作:

def open_file(file):
    with open(file,"r") as f:
        re = f.read()
        print(re)

使用with時,返回了一個上下文管理器,執行管理器的enter方法,如果with語句設置了目標對象,則把enter方法的返回值賦給目標對象,執行with中的代碼塊

使用python創建excel表格

下載相關庫:

pip install openpyxl
from openpyxl import Workbook

class Client(object):
    def __init__(self):
        #創建excel工作表
        self.wb = Workbook()
        #創建excel表裏的不同表單
        self.ws = self.wb.active
        
        #創建表單的三種方式
        self.ws.title = "表單1"
        self.ws_two = self.wb.create_sheet("表單2")
        self.ws_three = self.wb.create_sheet()

    def do(self):
  		#存儲excel表到相應路徑
        self.wb.save("./static/one.xlsx")
if __name__ == '__main__':
    client  = Client()
    client.do()

在這裏插入圖片描述
打開生成的excel文件,可以看出下面有三個表單,其中第三個表單未命名所以顯示默認名字

向excel表中手動寫入數據

from openpyxl.styles import Font, colors
from openpyxl.drawing.image import Image
#手動設置內容
        self.ws['A1'] = "學號"
        self.ws['B1'] = "姓名"
        self.ws['C1'] = "成績"
        self.ws['A2'] = "12345"

        #設置字體,顏色
        font = Font(sz = 18,color=colors.RED)
        self.ws['A2'].font = font

        #循環賦值
        i = 2
        for row in self.ws['A3':'C5']:
            for cell in row:
                cell.value = i
                i +=2

        #插入圖片
        image = Image("./static/shishi.png")
        self.ws.add_image(image,'E5')

        #合併/拆分單元格
        self.ws.merge_cells('A8:D9')
        self.ws.merge_cells('A11:D12')
        self.ws.unmerge_cells('A11:D12')
        #拆分單元格只能拆分之前已經合併過的

效果:
在這裏插入圖片描述
在這裏插入圖片描述

完整代碼:


from openpyxl import Workbook
from openpyxl.styles import Font, colors
from openpyxl.drawing.image import Image
class Client(object):

    def __init__(self):

        #創建excel工作表
        self.wb = Workbook()
        #創建excel表裏的不同表單
        self.ws = self.wb.active
        self.ws.title = "表單1"
        self.ws_two = self.wb.create_sheet("表單2")
        self.ws_three = self.wb.create_sheet()

    def do(self):

        #手動設置內容
        self.ws['A1'] = "學號"
        self.ws['B1'] = "姓名"
        self.ws['C1'] = "成績"
        self.ws['A2'] = "12345"

        #設置字體,顏色
        font = Font(sz = 18,color=colors.RED)
        self.ws['A2'].font = font

        #循環賦值
        i = 2
        for row in self.ws['A3':'C5']:
            for cell in row:
                cell.value = i
                i +=2

        #插入圖片
        image = Image("./static/shishi.png")
        self.ws.add_image(image,'E5')

        #合併/拆分單元格
        self.ws.merge_cells('A8:D9')
        self.ws.merge_cells('A11:D12')
        self.ws.unmerge_cells('A11:D12')

        self.wb.save("./static/one.xlsx")

if __name__ == '__main__':
    client  = Client()
    client.do()


將excel表中的數據存入數據庫

表的數據:
在這裏插入圖片描述

在數據庫中設定好相應參數:
在這裏插入圖片描述

python連接mysql數據庫
from openpyxl import Workbook, load_workbook
import MySQLdb

#數據庫連接
    def get_conn(self):
        conn = MySQLdb.connect(
            db = "user_grade",#數據庫名稱
            host = "localhost",#主機地址
            port = 3306,#端口號
            user = "root",#db登錄用戶名
            password = "root",#db登錄密碼
            charset = "utf8"
        )
        return conn
將excel中的數據寫入數據庫
#寫數據到數據庫
    def read_excel_to_db(self):
        #獲取要讀的excel表的表
        wb = load_workbook("./static/two.xlsx")
        name = wb.get_sheet_names()#獲取所有的表單名,這裏只有一個
        print(name)#成績統計

        ws = wb.active
        ws = wb[name[0]]

        for (i, row) in enumerate(ws.rows):
            if i < 1:
                continue
            com_org = ws['A{0}'.format(i+1)].value #數據從A2開始
            os = ws['B{0}'.format(i+1)].value
            micro_com = ws['C{0}'.format(i+1)].value
            mobile = ws['D{0}'.format(i+1)].value

            conn = self.get_conn()
            cursor = conn.cursor()
            sql = 'insert into `computer`(`com_org`,`os`,`micro_com`,`mobile`) VALUES ({com_org},{os},{micro_com},{mobile})'\
                .format(com_org=com_org,
                        os = os,
                        micro_com =  micro_com,
                        mobile = mobile)
            cursor.execute(sql)#執行插入的sql語句
            conn.autocommit(True)#提交

結果:
在這裏插入圖片描述

讀取數據庫中的數據將其寫入excel表中

    def export_from_db_to_excel(self):
        #查詢數據
        conn = self.get_conn()
        cursor = conn.cursor()
        sql = 'select `com_org`,`os`,`micro_com`,`mobile` from `computer`'
        cursor.execute(sql)
        rows = cursor.fetchall()
        #建立導出數據的excel表
        wb = Workbook()
        ws = wb.active
        ws['A1'] = "計算機組成原理"
        ws['B1'] = '操作系統'
        ws['C1'] = "微機原理"
        ws['D1'] = "移動設備開發應用"

        #將數據寫入表中
        row_id = 1
        for (i,row) in enumerate(rows):
            ws['A{0}'.format(row_id+1)] = row[0]
            ws['B{0}'.format(row_id+1)] = row[1]
            ws['C{0}'.format(row_id+1)] = row[2]
            ws['D{0}'.format(row_id+1)] = row[3]
            row_id += 1
            '''
            (
            ws['A{0}'.format(row_id+1)],
            ws['B{0}'.format(row_id+1)],
            ws['C{0}'.format(row_id+1)],
            ws['D{0}'.format(row_id+1)]
            ) = row
            '''
            
        wb.save("./static/export_data4.xlsx")

結果:
在這裏插入圖片描述

完整代碼


from openpyxl import Workbook, load_workbook
import MySQLdb

from openpyxl.styles import Font, colors
from openpyxl.drawing.image import Image

class Client(object):

    def __init__(self):

        #創建excel工作表
        self.wb = Workbook()
        #創建excel表裏的不同表單
        self.ws = self.wb.active
        self.ws.title = "表單1"
        self.ws_two = self.wb.create_sheet("表單2")
        self.ws_three = self.wb.create_sheet()


    #數據庫連接
    def get_conn(self):
        conn = MySQLdb.connect(
            db = "user_grade",#數據庫名稱
            host = "localhost",#主機地址
            port = 3306,#端口號
            user = "root",#db登錄用戶名
            password = "root",#db登錄密碼
            charset = "utf8"
        )
        return conn

    def export_from_db_to_excel(self):
        #查詢數據
        conn = self.get_conn()
        cursor = conn.cursor()
        sql = 'select `com_org`,`os`,`micro_com`,`mobile` from `computer`'
        cursor.execute(sql)
        rows = cursor.fetchall()
        #建立導出數據的excel表
        wb = Workbook()
        ws = wb.active
        ws['A1'] = "計算機組成原理"
        ws['B1'] = '操作系統'
        ws['C1'] = "微機原理"
        ws['D1'] = "移動設備開發應用"

        #將數據寫入表中
        row_id = 1
        for (i,row) in enumerate(rows):
            ws['A{0}'.format(row_id+1)] = row[0]
            ws['B{0}'.format(row_id+1)] = row[1]
            ws['C{0}'.format(row_id+1)] = row[2]
            ws['D{0}'.format(row_id+1)] = row[3]
            row_id += 1
            '''
            (
            ws['A{0}'.format(row_id+1)],
            ws['B{0}'.format(row_id+1)],
            ws['C{0}'.format(row_id+1)],
            ws['D{0}'.format(row_id+1)]
            ) = row
            '''

        wb.save("./static/export_data4.xlsx")


    #寫數據到數據庫
    def read_excel_to_db(self):
        #獲取要讀的excel表的表
        wb = load_workbook("./static/two.xlsx")
        name = wb.get_sheet_names()#獲取所有的表單名,這裏只有一個
        print(name)#成績統計

        ws = wb.active
        ws = wb[name[0]]

        for (i, row) in enumerate(ws.rows):
            if i < 1:
                continue
            com_org = ws['A{0}'.format(i+1)].value #數據從A2開始
            os = ws['B{0}'.format(i+1)].value
            micro_com = ws['C{0}'.format(i+1)].value
            mobile = ws['D{0}'.format(i+1)].value

            conn = self.get_conn()
            cursor = conn.cursor()
            sql = 'insert into `computer`(`com_org`,`os`,`micro_com`,`mobile`) VALUES ({com_org},{os},{micro_com},{mobile})'\
                .format(com_org=com_org,
                        os = os,
                        micro_com =  micro_com,
                        mobile = mobile)
            cursor.execute(sql)#執行插入的sql語句
            conn.autocommit(True)#提交

    def do(self):

        #手動設置內容
        self.ws['A1'] = "學號"
        self.ws['B1'] = "姓名"
        self.ws['C1'] = "成績"
        self.ws['A2'] = "12345"

        #設置字體,顏色
        font = Font(sz = 18,color=colors.RED)
        self.ws['A2'].font = font

        #循環賦值
        i = 2
        for row in self.ws['A3':'C5']:
            for cell in row:
                cell.value = i
                i +=2

        #插入圖片
        image = Image("./static/shishi.png")
        self.ws.add_image(image,'E5')

        #合併/拆分單元格
        self.ws.merge_cells('A8:D9')
        self.ws.merge_cells('A11:D12')
        self.ws.unmerge_cells('A11:D12')

        self.wb.save("./static/one.xlsx")



if __name__ == '__main__':
    client  = Client()
    #client.do()
    #client.read_excel_to_db()
    client.export_from_db_to_excel()



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章