用python處理Excel數據,實現Excel的功能:分列、透視等功能
1. Excel 解壓文件
#解壓tar_path中的壓縮文件到uzipPath def unzip_archive(tar_path): print('#######解壓文件夾,',tar_path) for i in os.listdir(tar_path): if i.endswith('zip'): print(i) shutil.unpack_archive(tar_path + "/" + i,unzipPath)
2. Excel的基本打開讀寫、獲取列
常見的Excel操作包括xlrd、pandas、xlwings,基本操作包括打開、讀取、獲取單元格值、寫入等
xlrd
data = xlrd.open_workbook(i) # 打開表 sheet = data.sheet_by_index(0) # 按照index獲取工作簿 sheet = data.sheet_by_name('sheet1') # 按照工作簿名獲取工作簿 nrows = sheet.nrows # 獲取行數 ncols = sheet.ncol # 獲取列數
row_value = sheet.row_values(i)
col_value = sheet.col_values(j)
用xlsxwriter寫入到Excel
划重點:write_row(row,col,data) 用了enumerate自動匹配索引和迭代的值
#將alist寫入tarfile的名為name的工作簿中 def insert_file(alist,tarfile,name='sheet1'): print("####將透視表寫入到",tarfile) wh = xlsxwriter.Workbook(tarfile) wadd = wh.add_worksheet(name) if len(alist) > 0 : for row_num,row_data in enumerate(alist): wadd.write_row(row_num,0,row_data)
補充:enumerate的用法
enumerate() 函數用於將一個可遍歷的數據對象(如列表、元組或字符串)組合為一個索引序列,同時列出數據和數據下標
代碼是示意結果
https://www.runoob.com/python/python-func-enumerate.html

alist = [['1','1-1'],['2','2-2'],['3','3-3']] for row_num, row_data in enumerate(alist): print(row_num,row_data)
pandas
xlwings
xlwings的好處在於可以直接獲得某列的指定位置的數據,缺點是 默認自動打開讀取的文件,甚至關了運行程序后台還是顯示這個文件是打開的……
設置visible之后 只是前段看不見,但是默認的還是會打開……
但是在獲取數據上還是很方便的
import xlwings as xw app = xw.App(visible=True, add_book=False) wb = app.books.open(file) #打開file sht = wb.sheets[0] dateLong = sht.range(f'H3:H{nrows}').value
3.數據透視表
# 根絕tarfile生成數據透視表 df = pd.read_excel(tarfile) pd.pivot_table(df,index=[u'日期',u'首次訪問'],values=[u'手機',u'會話效果'],aggfunc=[np.count_nonzero,np.count_nonzero])
參考鏈接:https://www.cnblogs.com/Yanjy-OnlyOne/p/11195621.html
但是這種方法寫出的透視表數據不美觀,后續需要調整,所以自己寫了個計數算法
算法思想是:空為0非空為1,計算
lista = [[0 if temp=='' else 1 for temp in list] for list in a] for i in range(len(a)): kl = a[i][:2] if type(kl[0]) == float or type(kl[0]) == int: kl[0] = getdate(kl[0]) # 從數字型日期轉為字符串型日期 key = (kl[0], kl[1]) #前兩列作為做透視的key val = lista[i][2:] #h后兩列是值 if key not in dicta.keys(): dicta[key] = val else: raw = dicta[key] dicta[key] = [raw[i] + val[i] for i in range(len(raw))] result = [list(key) + dicta[key] for key in dicta.keys()]
4. 獲取文件內的所有文件
def get_filename(tar_path): for root,dirs,files in os.walk(tar_path): for i in files: if i.endswith('xls') or i.endswith('xlsx'): print(i) dir.append(tar_path + "/" + i) print('#####解壓后的Excel文件',dir) return dir
這里深入了解了os的幾個常用函數,包括獲取指定目錄下的文件、

#獲取指定目錄下的文件夾或文件的名字列表 a = os.listdir(path) print(a) # 打開文件 f = os.open("",os.O_RDWR|os.O_CREAT) os.write(f,"this is test") #重命名 os.rename(src,dst) os.renames(old,new) #遞歸地更名 #刪除 os.remove(path) os.removedirs(path) #刪除遞歸目錄 #遍歷目錄 os.walk()