
4.3 使用pyexcel处理Office文件

在Python程序中,可使用pyexcel模块操作Excel和CSV文件,在使用pyexcel之前需要先安装pyexcel_xls,安装命令如下所示。

通过如下命令安装pyexcel。

4.3.1 使用pyexcel读取并写入CSV文件
在下面的实例文件office05.py中,演示了使用pyexcel读取并写入CSV文件的过程。
源码路径:daima\4\4-3\office05.py


在上述代码中,首先读取了文件example.csv中的内容,然后将指定的数据写入新建CSV文件tab_example.csv中。执行后的效果如图4-7所示。

图4-7 执行效果
4.3.2 使用pyexcel读取指定Excel文件中每个单元格数据
在下面的实例文件read_cell_by_cell.py中,演示使用pyexcel读取指定Excel文件中每个单元格数据的过程。
源码路径:daima\4\4-3\read_cell_by_cell.py

执行后的效果如图4-8所示。

图4-8 执行效果
4.3.3 按列读取并显示指定Excel文件中每个单元格数据
在下面的实例文件read_column_by_column.py中,演示了使用pyexcel按列读取并显示指定Excel文件中每个单元格数据的过程。
源码路径:daima\4\4-3\read_column_by_column.py

执行后的效果如图4-9所示。

图4-9 执行效果
4.3.4 读取显示Excel文件中的所有数据
如果在一个Excel文件中有多个Sheet,如文件在multiple-sheets-example.xls中有3个Sheet,里面的数据如图4-10所示。
通过下面的实例文件read_excel_book.py,可以读取显示上述multiple-sheets-example.xls文件中的所有数据。

图4-10 3个Sheet
源码路径:daima\4\4-3\read_excel_book.py

执行后会输出:

4.3.5 将3组数据导入新建的Excel文件
通过下面的实例文件write_excel_book.py,可以将3组数据导入新建的multiple-sheets1.xls文件中,3组数据分别对应于里面的3个Sheet。
源码路径:daima\4\4-3\write_excel_book.py

执行后会创建拥有3个Sheet的Excel文件,如图4-11所示。

图4-11 创建的Excel文件
4.3.6 以多种方式获取Excel数据
在下面的实例文件series.py中,演示了使用pyexcel以多种方式获取Excel数据的过程。
源码路径:daima\4\4-3\series.py


通过上述代码以多种方式获取了Excel中的数据,包括一维数组顺序和逆序、二维数组顺序和逆序。执行后会输出:

4.3.7 将数据分别导入Excel文件和SQLite数据库
在下面的实例文件import_xls_into_database_via_sqlalchemy.py中,演示了使用pyexcel将数据分别导入Excel文件和SQLite数据库的过程。
源码路径:daima\4\4-3\import_xls_into_database_via_sqlalchemy.py


执行后会输出:

4.3.8 在Flask Web项目中使用pyexcel处理数据
在下面的实例代码中,演示了在Flask Web项目中使用pyexcel处理数据的过程。
1)编写程序文件pyexcel_server.py,首先通过函数upload()实现文件上传功能,将上传的Excel文件导出为JSON格式显示在页面中;然后定义数据对象data,在里面保存了将要处理的数据;最后通过函数download()实现文件下载功能,使用data对象中的数据生成一个CSV文件并下载下来。文件pyexcel_server.py的具体实现代码如下所示。
源码路径:daima\4\4-3\memoryfile\pyexcel_server.py

2)编写模板文件upload.html实现了文件上传界面效果,具体实现代码如下所示。
源码路径:daima\4\4-2\memoryfile\templates\upload.html

在运行本实例程序之前确保已经安装gunicorn,然后通过如下命令运行本程序。

在浏览器中输入“http://127.0.0.1:5000/upload”后会显示文件上传界面,如图4-12所示。

图4-12 文件上传界面
单击“选择文件”按钮后选择一个上传文件,单击upload按钮后将在页面中显示上传文件的JSON格式数据,如图4-13所示。

图4-13 显示上传文件的JSON格式数据
在浏览器中输入“http://127.0.0.1:5000/download”后,会下载指定的CSV文件export.csv,这个文件中的数据是从data中导入并生成的。执行效果如图4-14所示。

图4-14 下载指定文件export.csv