Python 讀寫修改 Excle

1、初次創建 寫入 Excle

from time import sleep
import xlrd
from xlutils.copy import copy
import xlwt

class OperateExcle:
    def __init__(self):
        self.fileName = "test.xlsx"

    # 創建 一個 Excle ,並且寫入數據
    def creatWriteExcle(self):
        excle = xlwt.Workbook()  # 打開excel
        testSheet = excle.add_sheet('test')  # 添加一個名字叫test的sheet
        testSheet.write(0, 0, "小明")  # 在 0 行 0 列 寫入 小明
        testSheet.write(1, 0, "小黑")
        testSheet.write(2, 0, "小白")
        testSheet.write(0, 1, "小狗")
        testSheet.write(1, 1, "小貓")
        testSheet.write(2, 1, "小魚")
        excle.save(self.fileName)  # 保存 指定 路徑和文件名

if __name__ == "__main__":
    operate = OperateExcle()
    operate.creatWriteExcle() # 創建 和寫入 excle


創建如下:
在這裏插入圖片描述

2、讀取 Excle 內部數據

在這裏插入圖片描述

from time import sleep
import xlrd
from xlutils.copy import copy
import xlwt

class OperateExcle:
    def __init__(self):
        self.fileName = "test.xlsx"

    # 讀取 excle 內部數據
    def readExcle(self):
        excle = xlrd.open_workbook(self.fileName)  # 打開對應文件
        sheetData = excle.sheet_by_name("test")  # 根據名稱 獲取對應sheet
        row = sheetData.row_values(0)  # 獲取 0 行所有數據
        print("0 行",row)
        col = sheetData.col_values(0)  # 獲取 0 列所有數據
        print("0 列",col)
        data = sheetData.row_values(1)[1] # 獲取 1 行 1列的數據
        print("1 行 1 列",data)

if __name__ == "__main__":
    operate = OperateExcle()
    operate.readExcle()

在這裏插入圖片描述

3、修改已經存在的Excle

在這裏插入圖片描述

from time import sleep
import xlrd
from xlutils.copy import copy
import xlwt

class OperateExcle:
    def __init__(self):
        self.fileName = "test.xlsx"

    # 添加 或者 修改 已經存在的 Excle ,注意關閉 excle 文件
    def  modifyExcle(self):
        oldExcle = xlrd.open_workbook(self.fileName)  # 先打開已存在的表
        newExcle = copy(oldExcle)  # 複製 新的 文件
        newExcleSheet = newExcle.get_sheet(0)  # 根據 index 獲取 對應 sheet
        newExcleSheet.write(0, 0, "汪汪")  # 修改 0 行 0 列 爲 汪汪
        newExcleSheet.write(0, 5, "喵喵") # 添加 0 行 5 列 爲 喵喵
        newExcle.save(self.fileName)  # 保存新的文件 可以和原文件同名,則覆蓋原文件

if __name__ == "__main__":
    operate = OperateExcle()
    operate.modifyExcle()

當然 python 也可以 excle 進行 合併單元格 ,修改文字樣式 ,字體,背景,
設置 運算方式,添加超鏈接等。
更多操作就不在這裏寫出,只需要在此基礎上添加即可。

文件參考:
使用python將數據寫入excel

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