Python处理Excel生成CSV文档

Python是一种解释型的、动态数据类型的、面向对象的高级程序设计语言。拥有丰富的处理数据和文本类库,并且得益于它是一种解释型的语言,在程序修改和功能扩展上,可以很容易做到大规模的调整。综合考虑Python的动态、轻量化特性,使用Python来处理Excel自动生成CSV文档的操作。 程序的运行需要依赖两个Python的类库,Pandas和Xlrd。Pandas是Python的一个数据分析类库。Xlrd则是帮助开发人员从Microsoft的Excel操作数据的好帮手。

 

至于为什么要把Excel变成CSV就很简单了。由于CSV基于“,”符号切割字符串表单,因此,在程序上,读写访问非常方便。不需要导入厚重的Excel类库,只需要基于string数据结构就可以实现基本的表单管理。

一.Python和相关依赖库的配置步骤

1. 安装Python

请到Python官网下载并安装Python运行时:https://www.python.org/downloads/

2. 安装成功后,请打开Cmd控制台,输入如下命令安装Pandas

pip install pandas

 Python处理Excel生成CSV文档

 

3. 接着输入如下命令安装Xlrd

pip install xlrd

 Python处理Excel生成CSV文档

 

4. 如果你使用PyCharm,那么该工程的引用库安装导入方式如下:

    File -> Settings -> Project: [current project name] -> ProjectInterpreter -> +(Add Button) -> 弹出的搜索框里分别依次选中PandasXlrd

 Python处理Excel生成CSV文档

 

二.转换实现

在开始编码前,我们思考一下转换的流程:

 

  先收集所有的Excel文件 -> 遍历每一个Excel文件 -> Excel文件中还有众多的Sheet组成,也要遍历他们 -> 最终把Sheet为单位生成独立的CSV文件

 

那么接下来就是要研究那些API可以帮忙我们,如何获取目录文件集,如何打开excel文档,如何遍历sheet,如何保存成csv文档等等。这里就不流水账罗列过程了,直接贴出成品代码,下面的代码是上述思考过程的最终成品。最后,我们启动PyCharm运行脚本,显然当前脚本很好的搜索的指定的目录,并把所有表格的Sheet生成对应的CSV文档。 

 

对了,代码里面我还留一个彩蛋,如何遍历所有的表格单元。这个,可以很好的帮你处理非法的单元格数据,关键的代码就是调用dataframe的applymap方法。代码中示例输入的方法是foreach_cell,该方法的本体是将nan的数据变成0。

 

Python处理Excel生成CSV文档
import os
import math
import xlrd
import pandas as pd


def get_all_table_file_name(folder_path):
    table_names = []
    for file in os.listdir(folder_path):
        if os.path.splitext(file)[1] == '.xls' or os.path.splitext(file)[1] == '.xlsx':
            table_names.append(file)
    return table_names


def foreach_cell(cell):
        if type(cell) is float and math.isnan(cell):
            cell = 0
        return cell


def convert_table_to_csv(folder_path, file_name):
    file_path = folder_path + '/' + file_name
    print('开始转换Excel文档: ' + file_path + ' 成 CSV 文档')

    tables = xlrd.open_workbook(file_path)
    print('..Sheet总数: ' + tables.nsheets.__str__())

    for sheet_table in tables.sheets():
        csv_file_name = file_name.replace('.xlsx', '')
        csv_file_name = csv_file_name.replace('.xls', '')
        output_path = 'output/' + csv_file_name + sheet_table.name + ".csv"

        sheet = pd.read_excel(file_path, sheet_table.name, index_col=None, index=False)
        sheet.columns = sheet.columns.str.replace('Unnamed.*', '')
        sheet.applymap(foreach_cell)
        sheet.to_csv(output_path, encoding='utf-8', index=False)
        print('....已经生成 ' + csv_file_name + sheet_table.name + ' CSV文档')


def convert_all_tables_to_csv(folder_paths):
    for folder_path in folder_paths:
        table_files = get_all_table_file_name(folder_path)
        for table_file in table_files:
            convert_table_to_csv(folder_path, table_file)


scan_folders = ['.', 'tables']
convert_all_tables_to_csv(scan_folders)
Python处理Excel生成CSV文档

 

 

 

 Python处理Excel生成CSV文档

 

 Python处理Excel生成CSV文档

http://www.dhg3119.cn/
http://www.azd6793.cn/
http://www.vuf7734.cn/
http://www.ums9455.cn/
http://www.dli5822.cn/
http://www.rik3314.cn/
http://www.arf0717.cn/
http://www.dsx1888.cn/
http://www.dsd3012.cn/
http://www.pur5137.cn/
http://www.fsj6077.cn/
http://www.tvz4241.cn/
http://www.dxq9350.top/
http://www.xom4602.top/
http://www.dcj6843.top/
http://www.rew9011.top/
http://www.vrc3443.top/
http://www.xzg8926.top/
http://www.hrd7175.top/
http://www.njn2935.top/
http://www.gmn7922.top/
http://www.gdi2417.top/
http://www.dpz7007.top/
http://www.slg0631.top/
http://www.pzq0064.top/
http://www.jqg9208.top/
http://www.smp7329.top/
http://www.sqd7023.top/
http://www.bmh5849.top/
http://www.lwg3929.top/
http://www.wgt9662.top/
http://www.bux1348.top/
http://www.ukr4854.top/
http://www.cfs8763.top/
http://www.psd1092.top/
http://www.xck1603.top/
http://www.fgm4024.top/
http://www.zoj1707.top/
http://www.oiv1998.top/
http://www.ftw8814.top/
http://www.jfs6888.top/
http://www.kdx4817.top/
http://www.sbx6519.top/
http://www.rrq5611.top/
http://www.pxk9336.top/
http://www.vik6796.top/
http://www.kod8371.top/
http://www.nuq3623.top/
http://www.vfv3740.top/
http://www.tbt7039.top/
http://www.wky3695.top/
http://www.kcs3342.top/
http://www.gum4900.top/
http://www.mrw5927.top/
http://www.wnu1861.top/
http://www.vlc4617.top/
http://www.idv6045.top/