Python 版本
目前 Python 3 版本為主流版本,這里測試的版本是:Python 3.10.5。
常用庫說明
Python 操作 Excel 的常用庫有:xlrd、xlwt、xlutils、openpyxl、pandas。這里主要說明下 Excel 文檔 .xls 格式和 .xlsx 格式的文檔打開和讀取。
Python 操作 .xls 格式的 Excel
參考網址:xlrd — xlrd 2.0.1 documentationhttps://xlrd.readthedocs.io/en/latest/
import xlrd# 定義文件路徑并打開文件
filePath = r'C:\Users\mengll\Desktop\測試的EXCEL文檔.xls'
file = xlrd.open_workbook(filePath)# Excel Sheet 頁數量:file.nsheets
print("這個表格一共有的sheet數量是: {0}".format(file.nsheets))
# Excel Sheet 頁名列表:file.sheet_names()
print("這個表格sheet名是:{0}".format(file.sheet_names()))# Excel 第一個 Sheet 頁:file.sheet_by_index(0)
sheet0 = file.sheet_by_index(0)
# Sheet 頁的名稱、行數、列數是:sheet.name|sheet.nrows|sheet.ncols
print("{0} {1} {2}".format(sheet0.name, sheet0.nrows, sheet0.ncols))
# Sheet 頁指定單元格的值是:sheet.cell_value(rowx=1, colx=1)
print("單元格 A1 內容為:{0}".format(sheet0.cell_value(rowx=0, colx=0)))# 循環打印 Sheet 的所有行數據
for rx in range(sheet0.nrows):print(sheet0.row(rx))
Python 操作 .xlsx 格式的 Excel
參考網址:openpyxl - A Python library to read/write Excel 2010 xlsx/xlsm files — openpyxl 3.1.3 documentationhttps://openpyxl.readthedocs.io/en/stable/
import openpyxl# 定義文件路徑并打開文件
filePath = r'C:\Users\mengll\Desktop\測試的EXCEL文檔.xlsx'
file = openpyxl.load_workbook(filePath)# Excel Sheet 頁名列表:file.sheetnames
print("這個表格sheet名是:{0}".format(file.sheetnames))
print("這個表格sheet名是:{0}".format(file.worksheets))# Excel 第一個 Sheet 頁:file['sheet0']
sheet = file['sheet0']
# Sheet 頁的名稱、左上右下單元格、行數、列數是:sheet.title|sheet.dimensions|sheet.max_row|sheet.min_row|sheet.max_column|sheet.min_column
print("{0} {1} {2} {3}".format(sheet.title, sheet.dimensions, sheet.max_row, sheet.max_column))
# Sheet 頁指定單元格的值是:sheet.cell(row=1, column=1).value
print("單元格 A1 內容為:{0}".format(sheet.cell(row=1, column=1).value))
工具中其它很多屬性和用法,可以參考文檔自行嘗試,Good Luck~