首页 > 技术文章 > Python 与 excel的简单应用

nomorebug 2021-02-20 17:04 原文

1、pip openpyxl库:

pip install openpyxl -i http://pypi.douban.com/simple --trust-host pypi.douban.com

2、导入模块

import openpyxl

from openpyxl load_workbook

3、读取文件

1 wb = load_workbook(r'E:\****.xlsx')
2 shell = wb['Sheet1']

4、读取行、列、单元格:

row 行,以数字表示,从1开始
column 列,以字母表示,从A开始
cell 单元格
sheet 工作表

 读取行:shell[row]

print(shell[1])


-----------------------------------
(<Cell 'Sheet1'.A1>, <Cell 'Sheet1'.B1>, <Cell 'Sheet1'.C1>, <Cell 'Sheet1'.D1>, <Cell 'Sheet1'.E1>, <Cell 'Sheet1'.F1>)

读取列:shell['column']

print(shell['A'])    #这里的column需要用字母A、B、C等


--------------------------------------
(<Cell 'Sheet1'.A1>, <Cell 'Sheet1'.A2>, <Cell 'Sheet1'.A3>, <Cell 'Sheet1'.A4>, <Cell 'Sheet1'.A5>, <Cell 'Sheet1'.A6>, <Cell 'Sheet1'.A7>, <Cell 'Sheet1'.A8>, <Cell 'Sheet1'.A9>, <Cell 'Sheet1'.A10>, <Cell 'Sheet1'.A11>, <Cell 'Sheet1'.A12>, <Cell 'Sheet1'.A13>, <Cell 'Sheet1'.A14>, <Cell 'Sheet1'.A15>, <Cell 'Sheet1'.A16>, <Cell 'Sheet1'.A17>, <Cell 'Sheet1'.A18>, <Cell 'Sheet1'.A19>, <Cell 'Sheet1'.A20>, <Cell 'Sheet1'.A21>, <Cell 'Sheet1'.A22>, <Cell 'Sheet1'.A23>, <Cell 'Sheet1'.A24>, <Cell 'Sheet1'.A25>, <Cell 'Sheet1'.A26>, <Cell 'Sheet1'.A27>, <Cell 'Sheet1'.A28>, <Cell 'Sheet1'.A29>, <Cell 'Sheet1'.A30>, <Cell 'Sheet1'.A31>, <Cell 'Sheet1'.A32>, <Cell 'Sheet1'.A33>, <Cell 'Sheet1'.A34>, <Cell 'Sheet1'.A35>, <Cell 'Sheet1'.A36>, <Cell 'Sheet1'.A37>, <Cell 'Sheet1'.A38>, <Cell 'Sheet1'.A39>, <Cell 'Sheet1'.A40>, <Cell 'Sheet1'.A41>, <Cell 'Sheet1'.A42>, <Cell 'Sheet1'.A43>, <Cell 'Sheet1'.A44>, <Cell 'Sheet1'.A45>, <Cell 'Sheet1'.A46>, <Cell 'Sheet1'.A47>)

读取单元格: shell.cell(row,column)  or  shell['A1']

print(shell.cell(1,1))   #注意:这里的列号需要用数字

--------------------------------------
<Cell 'Sheet1'.A1>




print(shell['A1'])

---------------------------------------
<Cell 'Sheet1'.A1>

读取切片: shell['A1':'B5']

5、获取单元格的值:

   shell1['A1'].value  /shell.cell(1,1).value

6、获取切片的值:

    由于切片的类型是元组,因此不能直接用.value的方式来获得值,需要将其转化为可遍历的enumerate():

1 e1 = shell1['E32':'E38']
2 for index,item in enumerate(e1):
3     for cell in item :
4         value = cell.value
5         str = value[0]+'ROUND('+value[1:]+',0)'
6         cell.value = str

7、文件保存:

wb.save('filename')

 

9、自动给写好计算公式加入取整方法的代码:

#放入excel表中所在文件夹,修改数据切片位置
from openpyxl import load_workbook

#打开文件
wb = load_workbook('test.xlsx')
shell1 = wb['Sheet1']
#切片位置
e1 = shell1['C1':'C10']
#修改公式
for index,item in enumerate(e1):
    for cell in item :
        value = cell.value
        str = value[0]+'ROUND('+value[1:]+',0)'
        cell.value = str
wb.save('test2.xlsx')

 代码用法:

1、将上述代码用文本文件保存,按注释修改代码后,修改文件名为round.py,放到需要修改的表格文件同一文件夹内
2、文件夹内Shift+右键,菜单中选择“在此外打开Power Shell窗口“
3、输入python round.py
4、等待程序执行完毕后,查看文件平中新生成的xlsx文件;
以上,记录,以备脑力过衰不记事时查看【doge】

推荐阅读