from openpyxl import load_workbook
from openpyxl.styles import Alignment
from openpyxl import Workbook
# 创建excel 如果文件已存在,该方法会覆盖原内容,慎用
wb = Workbook('new1.xlsx')
wb.save('new1.xlsx')
# 加载已存在的excel, 更新里面的内容,不会清除原内容,文件不存在时抛出异常
wb = load_workbook('new.xlsx')
# wb.create_sheet('sh3',2)
# wb.remove(wb['sh31']) # 参数必须为sheet对象
# print(wb.active)
print(wb.sheetnames) # 获取所有的sheetnames列表
wb.copy_worksheet(wb['sh2'])
wb.save('new.xlsx')
Alignment对象: 用于设置cell对齐方式
from openpyxl.styles import Alignment
alignment = Alignment(horizontal='center', vertical='center')
ws.cell(1, 3).alignment = alignment
column_dimensions: 设置单元格宽度
ws.column_dimensions['D'].width = 12
wb = load_workbook('new1.xlsx')
ws = wb.active
# print(ws.active_cell)
# print(ws.cell(2, 2))
# print(ws.cell(2, 2, '4523'))
# print(ws.cell(2, 2).value)
# print(list(ws.rows)) # 先行 后列
# print(list(ws.columns)) # 先列 后行
# ws.insert_rows(0)
# ws.insert_cols(3)
# ws['C2'].value = '补贴'
# # print(list(ws.values))
# for i in range(1, len(list(ws.columns))+1):
# if i in (3,4):
# continue
# else:
# value = ws.cell(row=2, column=i).value
# ws.merge_cells(start_row=1,end_row=2,start_column=i,end_column=i)
# ws.cell(1, i, value=value)
# ws.merge_cells(start_row=1, end_row=1, start_column=3, end_column=4)
# ws.cell(1,3,'合并')
alignment = Alignment(horizontal='center', vertical='center')
for i in range(1, len(list(ws.columns))+1):
if i in (3,4):
continue
else:
ws.cell(1, i).alignment = alignment
ws.cell(1, 3).alignment = alignment
wb.save('new1.xlsx')
wb = load_workbook('new1.xlsx')
ws = wb.active
for i in list(ws.iter_rows(min_row=1,max_row=2)):
print(i)
for i in list(ws.values):
print(i)
print(ws[1:2])