openpyxl模块支持.xls和.xlsx格式的excel创建,但是只支持.xlsx格式的读取操作,不支持.xls的读取(可以使用xlrd模块来读取,写入操作也可使用xlwt模块),也可使用pandas模块对excel进行读写操作。
import openpyxl #创建工作簿 book=openpyxl.Workbook() # 创建表 table1=book.create_sheet(title="联系电话",index=0)#title表名;index:自定义表位置 table2=book.create_sheet("工作经历",3) #单元格值得插入(可以是具体值,也可以是excel函数语句) table1.cell(1,1,"手机号")#参数为:行,列,数值----表中的行和列都是以索引1开始计数,因此在定位单元格时行列都必须不小于1 table1['B1']='年龄' #单元格插入值的另外一种写法 for i in range(2,10): table1.cell(i,1).value=12345 table1.cell(i,2).value=i # 保存工作簿--可以指定xls或者xlsx book.save("员工信息.xlsx")#参数:文件名
import openpyxl
读取已有工作簿--注意只支持.xlsx,不支持.xls格式(可以用xlrd模块读取)
book = openpyxl.load_workbook("员工信息.xlsx")
table_list = book.worksheets print(table_list)
table_name_list = book.sheetnames print(table_name_list)
table_default = book.active # table_default=book.get_active_sheet print(table_default)
table = book['工作经历'] print(table) table = book.get_sheet_by_name("联系电话") print(table)
del book['Sheet']
book.create_sheet("sheet1") # book.create_sheet('sheet2')
table_name = table.title print(table_name)
rows = table.rows print(rows) # for row in table.rows: # for cell in row: # print(cell.value)
max_row = table.max_row print(max_row)
min_row = table.min_row print(min_row)
columns = table.columns print(columns) # for column in table.columns: # for cell in column: # print(cell.value)
max_column = table.max_column print(max_column)
min_column = table.min_column print(min_column)
values = table.values print(values) print(list(values))
定位单元格及获取值(三种方式都可)
cell = table.cell(1, 1) print(cell.value) cell = table['a1'] print(cell.value) cell = table['A1'] print(cell.value)
table.cell(2, 1).value = 12221231123 table.cell(3, 1, 29019219829) table['a3'] = 33234543246 table['A4'] = 432333333
book.save("员工信息.xlsx") book.close()
本文主要讲解了python使用openpyxl模块对excel的.xlsx格式文件读取操作,如果想操作xls格式文件,请使用xlrd,xlwt进行读写操作,更多关于python操作excel的文章请查看下面的相关链接