Python處理excel表格
阿新 • • 發佈:2019-01-08
工作遇見統計流量,只能把網頁裡的複製到excel表格裡,看到表格裡的資料無比的頭疼,只能用萬能的Python來解決(寫的很簡單又錯誤或者有更好方法可以指點指點):
下載安裝xlrd:
tar zxvf xlrd-0.9.4.tar.gz
cd xlrd-0.9.4
python setup.py install
>>> import xlrd #不報錯說明安裝成功
>>>
Python來操作excel檔案:
#!/usr/local/python2.7 import string import xlrd import os def read_excel(arg): data=xlrd.open_workbook(arg) #開啟檔案 sheet1_name=data.sheet_names()[0] sheet1 = data.sheet_by_name("Sheet1")#獲取sheet cols = sheet1.col_values(1)#獲取第三列 sum=0 for str in cols: if "GB" in str:#獲取符合的資料,再求和 data=str.split(" ")[0].replace(",","") sum += string.atof(data) return sum if __name__ == "__main__": while True: file_name=raw_input("Please Input you FileName:") if os.path.exists(file_name): print read_excel(file_name) else: print "The File Is Inexistence,Please Input FileName !!"
稍微改進了一下,只需要把excel檔案放到已知的目錄裡,輸入目錄名,就可以格式化輸出了:
#!/usr/local/python2.7 import string import xlrd import os def read_excel(dir): file_list=os.listdir(dir) for file in file_list: file_path=os.path.join(dir,file) data=xlrd.open_workbook(file_path) sheet1_name=data.sheet_names()[0] sheet1 = data.sheet_by_name("Sheet1") cols = sheet1.col_values(1) sum=0 for str in cols: if "GB" in str: data=str.split(" ")[0].replace(",","") sum += string.atof(data) print file,sum if __name__ == "__main__": Catalog_name=raw_input("Please Input you CatalogName:") if os.path.exists(Catalog_name): read_excel(Catalog_name) else: print "The File Is Inexistence,Please Input !!"