excel交叉表的數據清理

以前在作一個excel的簡單教程的時候:
B站的一個Excel簡單教程python

當時演示應該把交叉表(圖1)轉換成數據表格(圖2)的形式。app

圖1:交叉表

圖2:數據表

可是在excel裏沒有直接實現這個需求的函數,R的tidyr包有一個spread能夠實現這功能,可是,畢竟是R。ide

python一樣能夠實現這個需求,藉助openpyxl這個包和excel互動,而後用一點代碼就能夠完成了:函數

from openpyxl import Workbook,load_workbook
from openpyxl.utils import get_column_letter
wb = load_workbook('測試.xlsx')
ws = wb.active
rcList = tuple(ws.rows)
print(rcList)
def spreadIt(rcList,rowVarName='var1',colVarName='var2',cellVarName='var3'):
    rLength = len(rcList)
    cLength = len(rcList[0])
    rst = [[rowVarName,colVarName,cellVarName]]
    for i in range(1,rLength):
        for j in range(1,cLength):
            rst.append([rcList[i][0].value, rcList[0]
                        [j].value, rcList[i][j].value])
    return rst

def write2Sheet(spreaded,worksheet):
    for i in range(len(spreaded)):
        for j in range(len(spreaded[0])):
            worksheet["%s%d"%(get_column_letter(j+1),i+1)]=spreaded[i][j]

wbNew = Workbook()
wsNew = wbNew.active
write2Sheet(spreadIt(rcList,rowVarName='節數',colVarName='星期',cellVarName='課程'),wsNew)

wbNew.save(filename='test.xlsx')
相關文章
相關標籤/搜索