openpyxl
读写Excel文件
xls 是Excel 2007之前的版本,xlsx 是Excel 2007之后的版本,xlrd和xlwt 是用于较老的版本
openpyxl是官方推荐使用的第三方库.如果在Excel文件中插入图片之类的,需要pip install pillow
# 读取Excel文件
import openpyxl
import os
def get_file_path(filename):
base_dir = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
for root, dirs, files in os.walk(base_dir):
if filename in files:
return os.path.join(root, filename)
def read_worksheet(loc):
# loc 是Excel文件中的列,第一列就输入A,第三列就输出C即可
# A1表示第一列第一行,B2表示第二列第二行
filePath = get_file_path('TestData.xlsx')
wb = openpyxl.load_workbook(filePath)
sheet_ranges = wb['TestData'] # 'TestData' 表示的是sheetName
first_column = sheet_ranges[loc]
data = [first_column[x].value for x in range(1, len(first_column))]
return data
def write_data(row, column, data):
filePath = get_file_path('TestData.xlsx')
wb = openpyxl.load_workbook(filePath)
ws = wb.active
ws.cell(row= row, column=column).value = data
print(ws.max_row) # 总行数
wb.save(filePath)
write_data(row=len('A1')+1, column=1, data=100)
官方文档:https://openpyxl.readthedocs.io/en/stable/index.html
其他教程:
https://www.geeksforgeeks.org/python-writing-excel-file-using-openpyxl-module/?ref=lbp
https://www.javatpoint.com/python-openpyxl#AppendValues
https://blog.csdn.net/yaos829/article/details/103594988

浙公网安备 33010602011771号