美文网首页Python
Python中Excel转化CSV【原创】

Python中Excel转化CSV【原创】

作者: elijah777 | 来源:发表于2020-02-04 11:10 被阅读0次

    此文为连载内容,Excel操作第四篇,
    对Excel的其他操作请参考
    Python导出excel数据
    Excel读取并存入数据库通用处理
    Python对Excel读取

    四、Execl转CSV文件

    1、CSV写入

    import csv
    
    def writer():
        with open('D:/tmp/data/data.csv', 'w', newline='', encoding='utf-8-sig') as csvfile:
            spamwriter = csv.writer(csvfile)
            spamwriter.writerow(['HELLO', 'WORLD'])
    
    if __name__ == '__main__':
        writer()
        
    

    代码很简单,主要是传递的参数,参数形式也可以是多个数组,就是多行数据

    也可以是类似的写法

     writer.writerow(['id','name','age'])
     writer.writerow(['10001','elijah','20'])
     writer.writerow(['10002','Esther','22'])
     writer.writerow(['10003','jhon','21'])
    

    2、CSV转Execl

    # 读取Excel内容
    def read_input_ex():
        workbook = xlrd.open_workbook('D:/tmp/data/141.xls')  # (1)取得excel book对象
        sheet = workbook.sheet_by_name("Sheet1")  # (2)取得sheet对象
        rows = sheet.nrows  # (3)获得总行数
        title = sheet.row_values(0)
        data = []
        for r in range(1, rows):
            edata = []
            row = sheet.row_values(r)  # (4)获取行数据
            i = -1
            for t in title:
                i = i + 1
                edata.append(t)
                edata.append(row[i])
            print(edata)
            data.append(edata)
        return  data
     
       # 生成CSV 
     def writer_csv():
        data = read_input_ex();
        print("====")
        print(data)
        with open('D:/tmp/data/data.csv', 'w', newline='', encoding='utf-8-sig') as csvfile:
            spamwriter = csv.writer(csvfile)
            for d in data:
                spamwriter.writerow(d)   
    

    效果展示

    1580031112772.png 1580785567272.png

    2020/02/04于许昌

    相关文章

      网友评论

        本文标题:Python中Excel转化CSV【原创】

        本文链接:https://www.haomeiwen.com/subject/qgxrxhtx.html