Python操作excel

最近读取数据和帮助师兄师姐做一些简单的生信信息分析都需要用到excel解析数据,故对python操作excel的工具做个整理

使用哪个库?

其实一搜就发现,Python操作excel的各个教学博文蛮多的,主要就是xlrd、xlwt和openpyxl两类,接下来就主要讲讲如何评估二者

各个库的介绍

xlrd

跨平台的python模块,然后有特意提到他more like a native python coding style,且支持xls和xlsx,但是只是读取

( It is a Python Module for dealing with Excel files that can work on Windows, Linux as well as Mac platforms. It has more like a native python coding style and very helpful in accessing all types of excel files if they are xls or even xlsx. However it is used only for reading purposes. )

xlwt

算是xlrd的配套,仅支持Excel95-2003的编辑,所以xlwt不能写入超过65535行、256列的数据

也提到了他的风格是全python的,pythoner可能会更喜欢他的原生触感

( xlwt library allows developers to create spreadsheets compatible to Excel 95-2003. Hence we can say that it can be used for older files. Module is in pure Python form and exists as independent entity. Python programmers like to code in it as it has a native touch and taste. )

xlsxwriter

上面的xlwt只能支持到xls,但是现在大多是xlsx,这个库就是新增用于xlsx的使用

惊闻噩耗:它只能写入新文件!!!不可修改文档

( It is an alternative Python module for Writing data in Excel file. It specializes in formatting of data and it can also be used for charts in Excel 2010 xlsx formats. It is a wonderful package with many qualites, which if truly harnessed can do magic in terms of data writing and formatting. )

openpyxl

新的python操作excel库,主要由 Eric Gazoni and Charlie Clark开发,开源且免费,支持 Excel xlsx/xlsm/xltm/xltx files without using the Excel software,而且他是支持读写的,也就是不用像上述的库只能读或者写,介绍就主要讲了啥excel操作很复杂, it may take hours, and if the files are hundreds or thousands it can take days or sometimes weeks 但是你要是用了我们的库, you just write a simple program usually spending a few minutes and your hectic boring work is done by computer in no time ,牛逼吧。。。事实上我觉得很多时候,excel的很多工具和函数很方便的,主要是一方面看你哪方面比较厉害,另一方面是看你需不需要其他处理和接口

有一个不方便的,他不支持早期的xls

来源:

https://www.pythonexcel.com 

http://www.python-excel.org

其实很好奇这俩网站咋来的,然后前者网站感觉是openpyxl整的,因为吹了很多它,并且还有其教学课程的链接,10刀。。我甚至没找到他的reference链接,这个还挺烦的 = =

权衡

兼容性

首先openpyxl,一直被各种安利,我觉得好处是有的,毕竟比较新,而且进行了整合,读写同一个库,同时对各个版本的excel文件格式都兼容,这一点上还是有较大优势的

扩展性

openpyxl特意提到 openpyxl is the default reader for Python Pandas ,而且看reference里有很多关于panda、numpy的接口,比如讲worksheet直接转成dataframe等,这一点上,openpyxl的优点还挺明显的。当然,我还没用过xlrd,不知道他们的支持情况

性能

还有最关键的性能问题,这一点openpyxl还是挺老实的,自己坦白了说我们这个库,在权衡性能和功能上,选择了功能(致敬python?,所以性能上确实有欠缺,具体可以看https://openpyxl.readthedocs.io/en/stable/performance.html,就提到了openpyxl和xlrd/xlwt的比较,总体来说前者还是慢些,但是注意一点:可以再读写时注明只读或者只写,能快些,但是openpyxl在只写的时候,只能append,不能插入。

But

上面的都是通过手册和各个blog得出的结论,关于具体的性能和服务支持上,没有实际跑过,差距不好说,保留意见

最后选择

读取用xlrd,数据处理完存储好,然后用openpyxl写就好

openpyxl:

https://openpyxl.readthedocs.io/en/stable/tutorial.html Openpyxl Reference

xlrd:

https://xlrd.readthedocs.io/en/latest/api.html xlrd的reference

xlsxwriter:

https://xlsxwriter.readthedocs.io/index.html#

其他神仙

读写Excel文件第三方库汇总,你想要的都在这儿

参考:

https://www.pythonexcel.com

http://www.python-excel.org

https://www.pythonexcel.com/openpyxl.php Openpyxl Tutorial

0%