Basics

from openpyxl import Workbook,load_workbook

wb = Workbook() #创建空白工作簿
wb2 = load_workbook(r"filename.xlsx") #加载已有excel
ws = wb.active #激活worksheet
ws1 = wb.create_sheet("Mysheet") #在最后插入sheet
ws2 = wb.create_sheet("Mysheet",0) #在某个位置插入sheet
wb.remove("sheetname") #删除某工作表

ws3 = wb["Sheet Name"] #调用某个sheet
ws4 = wb.get_sheet_by_name("Sheet Name") #调用某个sheet
ws.sheet-properties.tabColor = "1072BA" #sheet名标颜色
ws.max_row #获取最大行
ws.max_column #获取最大列
wb.sheetnames #显示所有sheet name,返回一个list
for sheet in wb:
    print(sheet.title) #遍历sheet
    
cell = ws["A1"] #调用单元格
cell = ws.cell(row=4,column=2,value=10) #赋值单元格

cell_range = ws["A1":"C3"] #访问单元格域
cell_col = ws["C"] #访问某一列
cell_col_range = ws["C:F"] #访问多列
cell_row = ws[10] #访问某一行
cell_row_range = ws[3:9] #访问多行

for row in ws.iter_rows(min_row=1,max_row=10,
                        min_col=2,max_col=8,
                        values_only=False):
    for cell in row:
        print(cell)  #访问指定范围行遍历

for col in ws.iter_cols(min_row=1,max_row=10,
                        min_col=2,max_col=8,
                        values_only=False):
    for cell in col:
        print(cell) #访问指定范围列遍历
        
for row in sheet.rows:
    for cell in row:
        print(cell.value) #按行遍历
        
for column in sheet.columns:
    for cell in column:
        print(cell.value) #按列遍历
        
wb.save("filename.xlsx") #保存文件
        
from openpyxl.utils import get_column_letter,column_index_from_string

print(get_column_letter(2))
print(column_index_from_string("D"))

from openpyxl.styles import Font,colors,Alignment

bold_itatic_24_font = Font(name="等线",size=24,italic=True,color=colors.RED,bold=True)

sheet["A1"].font = bold_itatic_24_font #对单元格字体进行操作
sheet["B1"].alignment = Alignment(horizontal='center', vertical='center') #文本居中

sheet.row_dimensions[2].height = 40 # 设置行高
sheet.column_dimensions["C"].width = 30 # 设置列宽

sheet.merge_cells('B1:G1') # 合并一行中的几个单元格
sheet.merge_cells('A1:C3') # 合并一个矩形区域中的单元格
sheet.unmerge_cells('A1:C3') # 拆分单元格

你可能感兴趣的:(Basics)