今天來看如何使用python處理excel文件,處理excel文件是在工作中經常用到的,python為我們考慮到了這一點,python中本身就自帶csv模組。
1.用python讀取csv檔:
csv是逗號分隔符號格式一般我們用的execl產生的格式是xls和xlsx 直接重命名為csv的話會報錯:
Error: line contains NULL byte insun解決方案:出錯原因是直接是把後綴為xls的execl檔案重新命名為csv的正常的要是另存為csv檔案就不會報錯了
譬如我們有這麼個csv檔:
#!/usr/bin/env python # -*- coding:utf-8 -*- import csv with open('egg.csv','rb') as f: reader = csv.reader(f) for row in reader: print rowreee打印出來是這樣的list
#!/usr/bin/env python # -*- coding:utf-8 -*- import csv with open('egg2.csv', 'wb') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(['a', '1', '1', '2', '2']) spamwriter.writerow(['b', '3', '3', '6', '4']) spamwriter.writerow(['c', '7', '7', '10', '4']) spamwriter.writerow(['d', '11','11','11', '1']) spamwriter.writerow(['e', '12','12','14', '3'])了跟我們原本意圖存進5列不一樣使用python的csv生成excel所兼容的csv文件的話,主要就是創建writer時的參數時要有dialect='excel'代碼修改為:
#!/usr/bin/env python # -*- coding:utf-8 -*- import csv with open('egg2.csv', 'wb') as csvfile: spamwriter = csv.writer(csvfile,dialect='excel') spamwriter.writerow(['a', '1', '1', '2', '2']) spamwriter.writerow(['b', '3', '3', '6', '4']) spamwriter.writerow(['c', '7', '7', '10', '4']) spamwriter.writerow(['d', '11','11','11', '1']) spamwriter.writerow(['e', '12','12','14', '3'])