一、使用xlrd進(jìn)行讀操作打開(kāi)workbook wb = xlrd.open_workbook('mywokbook.xls')
檢查表單名字 wb.sheet_names()
獲取sheet表 sh = wb.sheet_by_index(0) # 索引獲取 sh = wb.sheet_by_name('Sheet01') # 名字獲取
遞歸打印所有行數(shù)據(jù) for n in range(sh.nrows):
返回第N列數(shù)據(jù) first_column = sh.col_values(N) 通過(guò)索引讀取某單元格數(shù)據(jù) cell_A1 = sh.cell(0, 0).value
二、使用xlwt進(jìn)行寫操作初始化workbook對(duì)象,之后才能進(jìn)行寫入操作 sheet = wbk.add_sheet('sheet2')
寫入數(shù)據(jù) sheet.write(0, 1, 'new text')
保存文件 注意:修改表單內(nèi)容,需要使用cell_overwrite_ok=True來(lái)創(chuàng)建worksheet sheet2 = wbk.add_sheet('sheet2', cell_overwrite_ok=True) sheet2.write(0, 0, 'text') sheet2.write(0, 0, 'altertext')
三、使用xlutils進(jìn)行修改操作Python中一般使用xlrd(excel read)來(lái)讀取Excel文件,使用xlwt(excel write)來(lái)生成Excel文件(可以控制Excel中單元格的格式),需要注意的是,用xlrd讀 取excel是不能對(duì)其進(jìn)行操作的:xlrd.open_workbook()方法返回xlrd.Book類型,是只讀的,不能對(duì)其進(jìn)行操作。而 xlwt.Workbook()返回的xlwt.Workbook類型的save(filepath)方法可以保存excel文件。因此對(duì)于讀取和生成Excel文件都非常容易處理,但是對(duì)于已經(jīng)存在的Excel文件進(jìn)行修改就比較麻煩了。不過(guò),還有一個(gè)xlutils(依賴于xlrd和xlwt)提供復(fù)制excel文件內(nèi)容和修改文件的功能。其實(shí)際也只是在xlrd.Book和xlwt.Workbook之間建立了一個(gè)管道而已,如下圖: 
xlutils.copy模塊的copy()方法實(shí)現(xiàn)這個(gè)功能 from xlrd import open_workbook from xlutils.copy import copy rb = open_workbook('D:\\text.xls') # 通過(guò)get_sheet()獲取的sheet才有write()方法 ws.write(0, 0, 'changed!')
四、實(shí)際工作使用將公司采購(gòu)單轉(zhuǎn)換成苗木平臺(tái)生成的Excel模板,采購(gòu)單總共76條數(shù)據(jù),模板14種苗木分類。 采購(gòu)數(shù)據(jù)樣式: 
苗木平臺(tái)模板數(shù)據(jù)樣式: 
生成的Excel表格 
偷了個(gè)懶,比如時(shí)間數(shù)據(jù)的格式?jīng)]進(jìn)行設(shè)置,實(shí)際代碼如下 from xlutils.copy import copy xl = xlrd.open_workbook(xl_name) xl_sheet = xl.sheets()[0] # 將原文件的采購(gòu)行插入匹配模板的采購(gòu)行 def insert_mb(L, line_no, ws): for i in range(mb_sheet.nrows): ws.write(line_no, i, tree_classify(one_tree[2])) ws.write(line_no, i, one_tree[2]) ws.write(line_no, i, one_tree[7]) ws.write(line_no, i, '43485') ws.write(line_no, i, tree_classify(str(one_tree[3]))) ws.write(line_no, i, one_tree[4]) ws.write(line_no, i, one_tree[5]) ws.write(line_no, i, one_tree[-1]) def tree_classify(tree_name): s = re.sub('[A-Z]', '', tree_name) def search_no(sheet, class_no): for i in range(len(col_data)): if class_no == 1 and col_data[i] == '一': elif class_no == 2 and col_data[i] == '二': elif class_no == 3 and col_data[i] == '三': elif class_no == 4 and col_data[i] == '四': elif class_no == 5 and col_data[i] == '五': elif class_no == 6 and col_data[i] == '六': # 讀取所有的采購(gòu)項(xiàng)并按序號(hào)分類 def load_class_no(class_no, sheet): for i in range(4, sheet.nrows-6): one_tree = sheet.row_values(i)[:-8] if one_tree[0] == class_no: if __name__ == '__main__': order_name = '副本徑河項(xiàng)目苗木采購(gòu)審批表.xlsx' mb_name = 'Copy of importBuyList_ex.xls' tree_sheet = open_sheet(order_name) mb_sheet = open_sheet(mb_name) col_data = mb_sheet.col_values(0) mb = xlrd.open_workbook(mb_name) wr_sheet = cp_sheet.get_sheet(0) class_trees = load_class_no(no, tree_sheet) line_no = search_no(wr_sheet, no) insert_mb(class_trees, line_no, wr_sheet)
|