Python實現讀取并寫入Excel文件過程解析
需求是有兩個Excel文件:1.xlsx,2.xlsx,比較2.xlsx中的A,B列和1.xlsx中的A,B列;查找1.xlsx中存在,2.xlsx中不存在的行數據,輸出到result.xlsx文件中
1.xlsx內容如下
2.xlsx內容如下
上代碼
# 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()可發現,返回的值為一個列表,通過對列表索引操作獲得工作表1# table = data.sheet_by_index(0)# 獲取行數和列數# 行數:table.nrows# 列數:table.ncols#print('總行數:' + str(table.nrows))#print('總列數:' + str(table.ncols))# 獲取整行的值 和整列的值,返回的結果為數組# 整行值:table.row_values(start,end)# 整列值:table.col_values(start,end)# 參數 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('總行數:' + str(table.nrows)) print('總列數:' + 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文件
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
