py讀寫修改Excel之xlrd&xlwt&xlutils

2021-03-10 12:00:50

py讀寫修改常用的三種方法

  • xlwt:用於寫入 Excel 檔案
  • xlrd:用於讀取 Excel 檔案
  • xlutils:用於操作 Excel 檔案的實用工具,比如複製、分割、篩選等

0、安裝模組

pip3 install xlrd xlwt xlutils

1. 寫入excel

  • git

    https://github.com/python-excel/xlwt/tree/master/examples
    
  • 實現效果
    在這裡插入圖片描述

  • 上程式碼

from datetime import datetime

import xlwt

font0 = xlwt.Font()

# font0.name = 'Times New Roman'  # 適用於字母或數位
font0.name = '宋體'    # 適用於中文,適配字型或者不指定字型才能體現出指定的顏色

# font0.colour_index = 1    # 白色
# font0.colour_index = 2    # 紅色
# font0.colour_index = 3    # 綠色
# font0.colour_index = 4    # 藍色
# font0.colour_index = 5    # 黃色
# font0.colour_index = 6    # 紫色
# font0.colour_index = 7    # 青色
# font0.colour_index = 8    # 黑色,比預設加黑,不加粗
font0.colour_index = 4    # 藍色
font0.bold = True

style0 = xlwt.XFStyle()
style0.font = font0

# 建立樣式物件:日期格式
style1 = xlwt.XFStyle()
style1.num_format_str = 'YYYY-MM-DD'

# 建立樣式物件:字型居中對齊
style2 = xlwt.XFStyle()
al = xlwt.Alignment()
al.horz = 0x02  # 設定水平居中
al.vert = 0x01  # 設定垂直居中
style2.alignment = al

# 建立樣式物件,設定日期格式與字型居中對齊
style3 = xlwt.XFStyle()
style3.num_format_str = 'YYYY-MM-DD'
style3.alignment = al

# 建立樣式物件,設定字型居中 且 設定字型顏色
style4 = xlwt.XFStyle()
style4.alignment = al
style4.font = font0

now_time = datetime.now().strftime('%Y-%m-%d %X')
date_time = datetime.now().strftime('%Y-%m-%d')

# 建立表格
wb = xlwt.Workbook()

# 新建一個名為 Score Sheet 的表單頁
score_sheet = wb.add_sheet('Score Sheet')

# 新建一個名為 Record Test Sheet 的表單頁
record_test_sheet = wb.add_sheet('Record Test Sheet')

# 1、寫入 Score Sheet 表單
# 設定 表頭, 第一個引數是行,第二個引數是列
score_sheet.write(0, 0, '時間', style2)
score_sheet.write(0, 1, '班級', style2)
score_sheet.write(0, 2, '姓名', style2)
score_sheet.write(0, 3, '語文', style2)
score_sheet.write(0, 4, '數學', style2)
score_sheet.write(0, 5, '英語', style2)
score_sheet.write(0, 6, '理綜', style2)
score_sheet.write(0, 7, '總分', style4)

# 按照位置新增資料
score_sheet.write(1, 0, datetime.now(), style3)
score_sheet.write(1, 1, '高三三班', style2)
score_sheet.write(1, 2, '桑巖', style2)
score_sheet.write(1, 3, 132, style2)
score_sheet.write(1, 4, 150, style2)
score_sheet.write(1, 5, 140, style2)
score_sheet.write(1, 6, 290, style2)
score_sheet.write(1, 7, xlwt.Formula("D2+E2+F2+G2"), style2)

score_sheet.write(2, 0, datetime.now(), style3)
score_sheet.write(2, 1, '高三三班', style2)
score_sheet.write(2, 2, '項天騏', style2)
score_sheet.write(2, 3, 140, style2)
score_sheet.write(2, 4, 150, style2)
score_sheet.write(2, 5, 132, style2)
score_sheet.write(2, 6, 280, style2)
score_sheet.write(2, 7, xlwt.Formula("D3+E3+F3+G3"), style2)

score_sheet.write(3, 0, datetime.now(), style3)
score_sheet.write(3, 1, '高三三班', style2)
score_sheet.write(3, 2, '向淮南', style2)
score_sheet.write(3, 3, 135, style2)
score_sheet.write(3, 4, 150, style2)
score_sheet.write(3, 5, 145, style2)
score_sheet.write(3, 6, 270, style2)
score_sheet.write(3, 7, xlwt.Formula("D4+E4+F4+G4"), style2)


# 2、寫入 Record Test Sheet 表單
record_test_sheet.write(0, 0, '時間')
record_test_sheet.write(0, 1, '學科', style1)
record_test_sheet.write(0, 2, '成績', style1)
record_test_sheet.write(1, 0, datetime.now(), style1)
record_test_sheet.write(1, 1, '語文', style2)
record_test_sheet.write(1, 2, 80)
record_test_sheet.write(2, 0, datetime.now(), style3)
record_test_sheet.write(2, 1, '數學', style2)
record_test_sheet.write(2, 2, 99)
record_test_sheet.write(3, 0, now_time, style2)
record_test_sheet.write(3, 1, '英語', style2)
record_test_sheet.write(3, 2, 98)


# 儲存表格,這裡應該是覆蓋寫,注意每次都是覆蓋所有表單內容,建議每次生成的表單加上時間版本區分
# wb.save('example.xls')
wb.save('example-{0}.xls'.format(date_time))

2、讀 Excel

  • git
    https://github.com/python-excel/xlrd
    
  • 實現效果,讀取sheet 表單內容

在這裡插入圖片描述

數值型別說明
0empty
1string字串
2number數位
3date日期
4boole布林值
5error錯誤
  • 上 程式碼
import xlrd

# 開啟 xls檔案
wb = xlrd.open_workbook("example-2021-03-09.xls")

# 獲取並列印 sheet 數量
print("sheet 數量:", wb.nsheets)         # sheet 數量: 2

# 獲取並列印 sheet 名稱
print("sheet 名稱:", wb.sheet_names())   # sheet 名稱: ['Score Sheet', 'Record Test Sheet']

# 根據 sheet 索引獲取內容
sh1 = wb.sheet_by_index(0)
# 或者
# 也可根據 sheet 名稱獲取內容
# sh = wb.sheet_by_name('Score Sheet')

# 獲取並列印該 sheet 行數和列數
print(u"sheet: %s表單 共 %d 行 %d 列" % (sh1.name, sh1.nrows, sh1.ncols))      # sheet: Score Sheet表單 共 4 行 8 列

# 獲取並列印某個單元格的值
print("第一行第二列的值為:", sh1.cell_value(0, 1))       # 第一行第二列的值為: 班級

# 獲取整行或整列的值
row_info = sh1.row_values(0)    # 獲取第一行內容
col_info = sh1.col_values(1)    # 獲取第二列內容

# 列印獲取的行列值
print("第一行的值為:", row_info)     # 第一行的值為: ['時間', '班級', '姓名', '語文', '數學', '英語', '理綜', '總分']
print("第二列的值為:", col_info)     # 第二列的值為: ['班級', '高三三班', '高三三班', '高三三班']

# 獲取單元格內容的資料型別,注意這裡的值 另有含義
print("第二行第一列的【值型別】為:", sh1.cell(1, 0).ctype)      # 第二行第一列的【值型別】為: 3

# 遍歷所有表單內容
for sh in wb.sheets():
    for r in range(sh.nrows):

        # 輸出指定行內容,這裡包含原有型別指定,不能直接獲取到指定列的值
        row_val_list = sh.row(r)
        print(row_val_list)
        # [text:'時間', text:'班級', text:'姓名', text:'語文', text:'數學', text:'英語', text:'理綜', text:'總分']

        # 遍歷行內,輸出當前行內的所有列值
        col_val_list = [col_val.value for col_val in row_val_list]
        print(col_val_list)

3、修改 Excel

修改 Excel 是通過 xlutils 庫的 copy 方法將原來的 Excel 整個複製一份,然後再做修改操作,最後再儲存

  • 修改前
    在這裡插入圖片描述

  • 修改後
    在這裡插入圖片描述

  • 上程式碼

import xlrd
from xlutils.copy import copy


# 開啟 excel 檔案, 帶格式複製
read_book = xlrd.open_workbook("example-2021-03-09.xls", formatting_info=True)

# 複製一份
wb = copy(read_book)

# 選取第一個表單
sh1 = wb.get_sheet(0)

# 在第五行新增寫入資料
sh1.write(4, 0, '2020-12-16')
sh1.write(4, 1, '高三三班')
sh1.write(4, 2, '小魚仙倌兒')
sh1.write(4, 3, 150)
sh1.write(4, 4, 150)
sh1.write(4, 5, 150)
sh1.write(4, 6, 300)

# 選取第二個表單
sh2 = wb.get_sheet(1)

# 替換總成績資料
sh2.write(1, 2, 100)

# 儲存
wb.save('example-2021-03-09.xls')

  • 注意,複製 xls這裡有格式問題

似乎沒有任何簡單的方法可以保留單元格的格式;它總是被吹走並設定為空白。

  • https://www.coder.work/article/80896
  • https://zhuanlan.zhihu.com/p/128674458

附錄

  • 參考:http://www.ityouknow.com/python/2019/12/29/python-excel-103.html
  • 官網:http://www.python-excel.org/