如何用python打开excel

silencement
Libérer: 2019-06-24 10:53:02
original
24530 人浏览过

如何用python打开excel

最近看到好几次群里有人问xlwt、wlrd的问题,怎么说呢,如果是office2007刚出来,大家用xlsx文件用不习惯,还可以理解,这都10年过去了喂,就算没有进化到office2016,还在用office2003的有点说不过去吧。有人可以用xlsx保存为xls啊!——故意多做几步操作,目的呢?为了兼容?兼容古老的office2003?而且,既然都用python来操作excel了,还要手动保存一遍文件,这是神马思路?

所以,我还是觉得,应该放弃xls而转型xlsx。所以才有了这篇文章——xlwt、wlrd只能读写xls文件,而不能操作xlsx文件。

解决方案:openpyxl。这是一个非常简单的库,有几分钟就能上手了。安装非常简单,pip install openpyxl一步搞定,我就主要来说说对excel的操作。当然,前面废话那么多,同学们差不多也能猜到了吧,openpyxl只能操作xlsx文件而不能操作xls文件。

1、基本概念

在openpyxl中,主要用到三个概念:Workbooks,Sheets,Cells。Workbook就是一个excel工作表;Sheet是工作表中的一张表页;Cell就是简单的一个格。openpyxl就是围绕着这三个概念进行的,不管读写都是“三板斧”:打开Workbook,定位Sheet,操作Cell。下面分读和写分别介绍几个常见的方法。

2、读取xlsx

为了做实验,我事先准备好了一个excel文档,里面有Sheet1,Sheet2,Sheet3这三个页,在Sheet3中填入了如下内容:

首先用

from openpyxl import load_workbook
Copier après la connexion

引入库

wb = load_workbook("template.xlsx")
Copier après la connexion

打开一个xlsx文件

print(wb.sheetnames)    # ['Sheet1', 'Sheet2', 'Sheet3']
Copier après la connexion

可以看看打开的Excel里有哪些sheet页

sheet = wb.get_sheet_by_name("Sheet3")
Copier après la connexion

读取到指定的Sheet页,sheet就变得神奇了,想要的内容都在这里。比如:

print(sheet["C"])    # (, , , , , , , , , )      <-第C列
print(sheet["4"])    # (, , , , )     <-第4行
print(sheet["C4"].value)    # c4     <-第C4格的值
print(sheet.max_row)    # 10     <-最大行数
print(sheet.max_column)    # 5     <-最大列数
for i in sheet["C"]:
  print(i.value, end=" ")    # c1 c2 c3 c4 c5 c6 c7 c8 c9 c10     <-C列中的所有值
Copier après la connexion

写入xlsx

首先用

from openpyxl import Workbook
wb = Workbook()
Copier après la connexion

创建一个工作表,然后

sheet = wb.active
Copier après la connexion

找到活动的sheet页。空的excel表默认的sheet页就叫Sheet,如果想改名字,可以直接给title属性赋值。

sheet.title = "New Shit"
Copier après la connexion

这个属性是可读可写的。当然,这个只针对当前活动页,别的页的话,可以用create_sheet和remove_sheet进行添加和删除。

往sheet页里面写内容就比较简单了,跟上面读一样,

sheet['C3'] = 'Hello world!'
for i in range(10):
  sheet["A%d" % (i+1)].value = i + 1
Copier après la connexion

我们还可以进行花式操作,比如写写公式:

sheet["E1"].value = "=SUM(A:A)"
Copier après la connexion

最后记得保存

wb.save('保存一个新的excel.xlsx')
Copier après la connexion

以上是如何用python打开excel的详细内容。更多信息请关注PHP中文网其他相关文章!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!