Python實現(xiàn)讀取并寫入Excel文件過程解析
需求是有兩個Excel文件:1.xlsx,2.xlsx,比較2.xlsx中的A,B列和1.xlsx中的A,B列;查找1.xlsx中存在,2.xlsx中不存在的行數(shù)據(jù),輸出到result.xlsx文件中
1.xlsx內(nèi)容如下
2.xlsx內(nèi)容如下
上代碼
# coding=utf-8import xlrdimport xlwt# 打開文件#data = xlrd.open_workbook(’./附件7:溶洞鉆孔、埋管、注漿.xlsx’)# 查看工作表#data.sheet_names()#print('sheets:' + str(data.sheet_names()))# 通過文件名獲得工作表,獲取工作表1#table = data.sheet_by_name(’20200404’)# 打印data.sheet_names()可發(fā)現(xiàn),返回的值為一個列表,通過對列表索引操作獲得工作表1# table = data.sheet_by_index(0)# 獲取行數(shù)和列數(shù)# 行數(shù):table.nrows# 列數(shù):table.ncols#print('總行數(shù):' + str(table.nrows))#print('總列數(shù):' + str(table.ncols))# 獲取整行的值 和整列的值,返回的結果為數(shù)組# 整行值:table.row_values(start,end)# 整列值:table.col_values(start,end)# 參數(shù) start 為從第幾個開始打印,# end為打印到那個位置結束,默認為none#print('整行值:' + str(table.row_values(0)))#print('整列值:' + str(table.col_values(1)))# 獲取某個單元格的值,例如獲取B3單元格值#cel_B3 = table.cell(3,2).value#print('第三行第二列的值:' + cel_B3)def read_xlrd(excelFile,tablename): data = xlrd.open_workbook(excelFile) #table = data.sheet_by_index(0) table = data.sheet_by_name(tablename) print('總行數(shù):' + str(table.nrows)) print('總列數(shù):' + str(table.ncols)) dataFile = [] for rowNum in range(table.nrows): # if 去掉表頭 if rowNum > 0: dataFile.append(table.row_values(rowNum)) return dataFile workbook = xlwt.Workbook(encoding = ’ascii’)worksheet = workbook.add_sheet(’sheet1’)def writeLine(row ,line): col=0 while col <len(line): worksheet.write(row,col, line[col]) col+=1filename1=’./附件7:溶洞鉆孔、埋管、注漿.xlsx’ data1=read_xlrd(filename1,’20200404’)filename2=’./設計之都溶洞注漿臺賬.xlsx’ data2=read_xlrd(filename2,’Sheet1’)data=[]for row in data1[4:]: #print(row[0],row[1]) data.append([row[0],row[1]])#print(data)result=[]i=0for row in data2[1:]: buf=[row[1],row[2]] if buf not in data: print(row,’不存在’) writeLine(i, row) i+=1workbook.save(’result.xlsx’)
之后生成結果result.xlsx文件
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
1. HTML <!DOCTYPE> 標簽2. 使用EF Code First搭建簡易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移3. HTML5 Canvas繪制圖形從入門到精通4. 低版本IE正常運行HTML5+CSS3網(wǎng)站的3種解決方案5. Django中如何使用Channels功能6. Vue ElementUI實現(xiàn):限制輸入框只能輸入正整數(shù)的問題7. 基于Python下載網(wǎng)絡圖片方法匯總代碼實例8. .NET Core中使用gRPC的方法9. php對gb編碼動態(tài)轉(zhuǎn)utf-8編碼的幾種方法評測10. 基于JavaScript實現(xiàn)大文件上傳后端代碼實例
