今天來看一下如何使用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 row
列印出來是這樣的list
['a', '1', '1', '1']
['a', '2', '2', '2']
['b', '3', '3', '3']
['b', '4', '4', '4']
['b', '5', '5', '5']
['b', '6', '6', '6']
['c', '7', '7', '7']
['c', '8', '8', '8']
['c', '9', '9', '9']
['c', '10', '10', '10']
['d', '11', '11', '11']
['e', '12', '12', '12']
['e', '13', '13', '13']
['e', '14', '14', '14']
2.用python寫入並生成csv
#!/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'])