openpyxl中的三個概念:
workbooks:excel工作表
sheets:工作表中的一張表頁
cells:表中的一個格子
使用openpyxl操作excel的三個步驟:打開workbooks攘轩、定位sheet植酥、操作cell
打開工作表&查看指定的內(nèi)容
1、打開表格文件
wb = openpyxl.load_workbook(“file_path/file_name”)
2辛藻、查看有哪些sheet頁,兩種方法等同
①sheet_names = wb.sheetnames
②sheet_names =wb.get_sheet_names()
3羹饰、讀取指定的sheet頁著榴,①②兩種方法等同
①sheet = wb.get_sheet_by_name(“sheet_name”)
②sheet = wb[“sheet_name”]
不知道表名時,先獲取表名列表引矩,用索引打開
sheet_names =wb.get_sheet_names()
ws =wb.get_sheet_by_name(sheet_names[0 or 1 or other])
或者
ws = wb.active打開第一個活動的表
4、單元格的使用
讀
①c = ws[‘A1’]
②c = ws.cell[‘A1’]
③c = ws.cell(row =1,column = 1)
寫
①ws[‘A1’] = 4
②ws.cell(row = 4,column =2).value = 3
③ws.cell[‘A1’] = 3
讀取多個單元格的數(shù)據(jù)
cell_range = ws[‘A1’:’C2’]
讀取所有單元格數(shù)據(jù)
get_cell_collection()
5侵浸、打印表中指定的數(shù)據(jù)
wb = openpyxl.load_workbook(“file_path/file_name”)
ws = wb[“sheet_name”]
print(ws[“row_num” or “column_num”])可以打印指定的行數(shù)或者列數(shù)的數(shù)據(jù)
print(ws [“row_num_num” or “clumn_num_num”].value)可以打印指定格數(shù)的值
print(ws.max_row)打印最大行數(shù)
print(ws.max_column)打印最大列數(shù)
6旺韭、建新表
wb = openpyxl.load_workbook(“file_path/file_name”)
ws1 = wb.create_sheet()新表插入到表末尾
ws2 = wb.create_sheet(0)新表插入到表頭
ws.title = “new title”修改表名稱
7、創(chuàng)建新表到寫入xlsx
wb = openpyxl.Workbook()創(chuàng)建一個工作表
sheet = wb.active找到活動的sheet頁
sheet.title = “New Shit”改sheet名
sheet[“row_num_num” or “clumn_num_num”]= value將值寫入表格中
wb.save(‘workbook_name.xlsx’)表格保存