1、打开表格文件
from openpyxl import load_workbook
wb = load_workbook(r"文件路径工作簿文件全名")
2. 查看有哪些sheet页
sheet_names = wb.sheetnames
print(sheet_names)
3. 读取指定的sheet页
sheet1 = wb['指定工作表的名字']
4.单元格的使用
#写
sheet1.cell(row=3,column=1,value=10)
wb.save('工作簿文件全名')#读的两种方法
#c=sheet1['A1']
#读取多个单元格的数据
#cell_range = sheet1['A1':'C2']
#读取所有单元格数据
cell_range = sheet1['A1':'C2']
#读取所有单元格数据
get_cell_collection()#打印最大列数
print(sheet1.max_column)
#打印最大行数
print(sheet1.max_row)
此处的写入保存显示正常,但是实际文本却没有写入。。。
有知道如何写入保存成功的麻烦私信我或留言。谢谢!
5. 当打开或保存excel文件时,必须指定正确的后缀和必要的参数,否则将打开或保存失败。如以下操作均会失败:
#如果直接保存xlsx文件时,需指定xlsx后缀,否则保存的文件打不开
wb = load_workbook('document.xlsx') # 启用宏的xlsm格式文件需指定参数:keep_vba=True, 否则保存的文件打不开
wb.save('new_document.xlsm')
wb = load_workbook('document.xltm', keep_vba=True) # 如果要保存为模板文件需指定后缀为xlsm,并且指定参数as_template=True,否则保存的文件打不开
wb.save('new_document.xlsm', as_template=True)
此处的as_template 使用时显示“TypeError: save() got an unexpected keyword argument 'as_template'”
有知道如何使用as_template 不显示语法错误的麻烦私信我或留言。谢谢!