excel 與 csv格式文件互相轉換------贈送《PyInstaller打包實戰指南》

 

有這一個指導就夠了

《PyInstaller打包實戰指南》
https://zhuanlan.zhihu.com/p/86956717

 

批量將 csv 轉換爲 xls

1.csv 2.csv 3.csv  等多個csv文件轉換爲 含多個sheet項目表的excel文件,同時支持excel2003 和 excel2007兩種格式

# using python3.x
import os
import re
import pandas as pd # csv to xls

def exec_csv_to_xls():
    allCSVFileNames = {}
    print("Current Path: " + os.getcwd())
    filenames = os.listdir(os.getcwd())
    for name in filenames:
        if not name.endswith('.csv'):
            continue
        result = re.match("\d+",name)
        if None != result:
            index = result.group()
            allCSVFileNames[int(index)] = name
        elif r'填寫必讀' in name:
            allCSVFileNames[0] = name

    print("----All csv File Num: %d" % len(allCSVFileNames))
    print("----Files:")
    print(allCSVFileNames)

    xlsx_writer = pd.ExcelWriter(os.path.join(os.getcwd(), "softwarePara.xls"), mode='a')# pd.ExcelWriter 默認使用 xlrd 引擎, 支持 excel 2003 xls格式
    for i in range(len(allCSVFileNames)):
        try:
            data = pd.read_csv(os.path.join(os.getcwd(), allCSVFileNames[i]), encoding='utf-8')
        except Exception as e:
            # print( "warning: Read file %s failed by utf-8, because %s" % (os.path.join(os.getcwd(), allCSVFileNames[i]),e))
            try:
                # print("warning: Will try read this file by gbk again !")
                data = pd.read_csv(os.path.join(os.getcwd(), allCSVFileNames[i]), encoding='gbk')
            except Exception as e:
                print("error: Read csv file %s failed, both by gbk or utf-8" % os.path.join(os.getcwd(), allCSVFileNames[i]))
                print("---- Convert csv to xls failed !!! ----")
                return #read csv by gbk 和 utf-8 均失敗, 不再生成excel 文件
            else:
                print("warning: %s is not uft-8, read by gbk successed !" % os.path.join(os.getcwd(), allCSVFileNames[i]))

        data.to_excel(xlsx_writer, sheet_name=allCSVFileNames[i].split('.')[0], index = False)
    print("---- Convert all csv to xls successed !!! ----")
    xlsx_writer.save()

if __name__=='__main__':
    print("----------- start to convert csv to excel -----------")
    exec_csv_to_xls()
    print("----------- convert finished -----------")

將包含多個sheet工作表的 xls 轉換爲多個csv文件

# -*- coding: utf-8 -*-
# using python3.x
import xlrd
import os
import time
import pandas as pd # xls to csv


def xls_to_csv(filepath):
    workbook = xlrd.open_workbook(filepath)
    sheets = workbook.sheet_names()
    print("工作表名稱:" + str(sheets))
    for i in range(len(sheets)):
        newCSVSheetName = sheets[i].strip() + '.csv'
        print(newCSVSheetName)
        data = pd.read_excel(filepath, sheets[i], dtype=object)
        data.to_csv(newCSVSheetName, index = False, encoding='UTF-8', sep=',', index_label=False)
        print(newCSVSheetName," created!")

if __name__=='__main__':
    st = time.time()
    print("Current Path: " + os.getcwd())
    filepath = os.path.join(os.getcwd(), "softwarePara.xls")
    xls_to_csv(filepath)
    print("Completed to convert ",filepath," to csv files!")
    nd = time.time()
    tm = nd - st
    print("Spend time: ",tm,"s")

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章