openpyxl学习笔记(2020-08-08)

openpyxl简单操作

from openpyxl import Workbook
# 导入模块

wb = Workbook()
# 实例化对象,不需要打开xlsx文件,在最后保存时指定即可

ws = wb.active
# 在xlsx文件中新建了一个sheet,默认命名

ws1 = wb.create_sheet('my first sheet')
# 新建一个sheet,可指定命名,然则默认命名

ws.title = 'initial sheet'
# 已创建的sheet名称可被修改

ws.sheet_properties.tabColor = '1072BA'
# 可设定sheet的颜色

print(wb.sheetnames)
# 可查看wb的所有sheet名

for sheet in wb:
	print(sheet.title)
# 亦可通过遍历查看

source = wb['my first sheet']
target = wb.copy_worksheet(source)
# 可在同一个workbook里复制sheet内容,仅限表格信息,图片、图表等信息会缺失,也不可在workbooks之间复制

c = ws['A5']
# 获取到ws sheet中的A5 表格位置,进而进行编辑

ws['A5'] = 5
# 进行赋值,c = 5 亦可

d = ws.cell(row=4, col=2, value=10)
# 亦可通过行列进行赋值

cell_range = ws['A1':'B3']
# 利用切片圈取一堆表格

colC = ws['C']
col_range = ws['C:D']
row10 = ws[10]
row_range = ws[5:10]
# 获取整行整列

for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
	for cell in row:
	print(cell)
# 遍历输出表格,按行输出

for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
	for cell in col:
	print(cell)
# 按列遍历输出表格

print(tuple(ws.rows))
print(tuple(ws.cols))
# 遍历所有

for row in ws.values:
	for value in row:
		print(value)
# 遍历所有表格的值

for row in ws.iter_rows(min_row=1, max_col=3, max_row=4, values_only=True):
	print(row)
# 遍历指定表格的值

c.value = 'hello botany'
# 赋值

wb.save('tutorial.xlsx')
# 保存xlsx文件,同名会覆盖


你可能感兴趣的:(python文档操作,python,excel)