from openpyxl import load_workbook
from openpyxl.styles import Font,colors, Alignment
from openpyxl.styles import Border, Side
#打开已经存在的Excel
workbook = load_workbook(filename='C:\\Users\\yh\\Documents\\测试.xlsx')
#创建表(sheet),插入到最后(default)
ws1 = workbook.create_sheet("Mysheet")
#创建表(sheet),插入到最开始的位置
ws2 = workbook.create_sheet("Mysheet2",0)
print(workbook.sheetnames)
#根据名称获取工作表
sheet = workbook['1']
#获取表格内容所在的范围
print(sheet.dimensions)
# 获得最大列和最大行
print(sheet.max_row)
print(sheet.max_column)
#获取某个单元格的具体内容
#获取每一行,每一列
# 因为按行,所以返回A1, B1, C1这样的顺序
for row in sheet.rows:
for cell in row:
print(cell.value)
# A1, A2, A3这样的顺序
for column in sheet.columns:
for cell in column:
print(cell.value)
#指定坐标
cell=sheet['A1']
print(cell.value)
#指定行列
cell1=sheet.cell(row=6,column=5)
print(cell1.value)
#获取某个单元格的行、列、坐标
print(cell.row, cell.column, cell.coordinate)
#设置行高和列宽
sheet.row_dimensions[6].height = 200
sheet.column_dimensions['C'].width = 50
#写入单元格
cell3 = sheet['B1']
cell3.value = '业务需求'
# 合并
#sheet.merge_cells('B2:D5')
#sheet.merge_cells(start_row=1, start_column=3,
# end_row=2, end_column=4)
# 取消合并
sheet.unmerge_cells('B2:D5')
#sheet.unmerge_cells(start_row=1, start_column=3,
# end_row=2, end_column=4)
# 下面的代码指定了等线24号,加粗斜体,字体颜色红色。直接使用cell的font属性,将Font对象赋值给它。
bold_itatic_24_font = Font(name='等线', size=24, italic=True, color=colors.RED, bold=True)
sheet['A1'].font = bold_itatic_24_font
#保存Excel
workbook.save(filename='C:\\Users\\yh\\Documents\\测试.xlsx')
python操作.xlsx文件
最新推荐文章于 2024-08-31 07:11:56 发布