Python自动化之Excel
Excel读取
读取对应表格
读取单元格
读取多个格子的值
Excel写入
最近太忙,暂且只整一部分,后续补上
读取对应表格
- 打开已经存在的Excel表格
from openpyxl import load_workbook#获取表格内所有的sheet
exl = load_workbook(filename = r'C:\Users\晴天\Desktop\目录文件.xlsx')
#运行解压错误,需要在路径前加 r
print(exl.sheetnames)
['学习文件目录', 'Sheet1']
- 根据名称获取表格
from openpyxl import load_workbook
exl_1 = load_workbook
(filename = r'C:\Users\晴天\Desktop\测试数据.xlsx')
print(exl_1.sheetnames)
sheet = exl_1['产品销售']
#在excel 工作薄中只有一张表可以根据名称获取
sheet = exl_1.active
['产品销售']
- 获取Excel 内容占据的大小
print(sheet.dimensions)
A1:N78263
读取单元格
- 获取某个单元格的具体内容
cell = sheet.cell(row=1,column=4)
#指定行列数 ,cell单元格,column列,row行
print(cell.value)
cell_1 = sheet['A1'] #指定坐标
print(cell_1.value)
客户编号
订单编号
- 获取单元格对应的行、列和坐标
print(cell_1.row, cell_1.column, cell.coordinate)
1 1 D1
读取多个格子的值
- 指定坐标范围
A= sheet['A1:C8'] #A1到C8区域的值
print(A)
((<Cell '产品销售'.A1>, <Cell '产品销售'.B1>, <Cell '产品销售'.C1>), (<Cell '产品销售'.A2>, <Cell '产品销售'.B2>, <Cell '产品销售'.C2>), (<Cell '产品销售'.A3>, <Cell '产品销售'.B3>, <Cell '产品销售'.C3>), (<Cell '产品销售'.A4>, <Cell '产品销售'.B4>, <Cell '产品销售'.C4>), (<Cell '产品销售'.A5>, <Cell '产品销售'.B5>, <Cell '产品销售'.C5>), (<Cell '产品销售'.A6>, <Cell '产品销售'.B6>, <Cell '产品销售'.C6>), (<