注釋較為全面餐胀,參照注釋使用即可。
庫的安裝: 從官網(wǎng)下載源碼后瘤载,解壓否灾,cmd進到對應目錄下,執(zhí)行 python setup.py install 即可鸣奔。
注意:1. xlrd 只能對文件進行讀墨技。2. xlwt 只能寫。3. 兩者的文件對象不能直接通用挎狸。
'''
# -*- coding: utf-8 -*-
import xlrd
import xlwt
from datetime import date,datetime
def edit_and_sava_as_excel():
workbook = xlrd.open_workbook(r'C:\Users\LiYang\Desktop\1.xls')? # 獲取所有sheet
print workbook.sheet_names() # [u'Sheet1', u'Sheet2']
sheet1_name = workbook.sheet_names()[0]
sheet1 = workbook.sheet_by_name('Sheet1')
print sheet1.name," row="+str(sheet1.nrows)," clo="+str(sheet1.ncols)
wbk2 = xlwt.Workbook()
sheet2 = wbk2.add_sheet('Sheet2')
for i in range(2,sheet1.nrows):
row = sheet1.row_values(i)? ? # 獲取第i行內容
if row[2] == u'\u5973\u751f':? # 如果是女生
row[3] = 'F'+row[3]
for j in range(4,7):
if row[j] != u'':
row[j] = 'M'+row[j]
else:
row[3] = 'M'+row[3]
for j in range(4,7):
if row[j] != u'':
row[j] = 'F'+row[j]
for j in range(0,7):
sheet2.write(i,j,row[j])
wbk2.save(r'C:\Users\LiYang\Desktop\2.xls')
def read_excel():? # 打開文件
workbook = xlrd.open_workbook(r'C:\Users\LiYang\Desktop\2.xls')? # 獲取所有sheet
print workbook.sheet_names() # [u'Sheet1', u'Sheet2']
sheet1_name = workbook.sheet_names()[0]
# 根據(jù)sheet索引或者名稱獲取sheet內容
#sheet2 = workbook.sheet_by_index(1) # sheet索引從0開始
sheet1 = workbook.sheet_by_name('Sheet2')
# sheet的名稱扣汪,行數(shù),列數(shù)
print sheet1.name," row="+str(sheet1.nrows)," clo="+str(sheet1.ncols)
# 獲取整行和整列的值(數(shù)組)
#rows = sheet1.row_values(3) # 獲取第四行內容
cols4 = sheet1.col_values(3) # 獲取四列內容
cols5 = sheet1.col_values(4)
cols6 = sheet1.col_values(5)
cols7 = sheet1.col_values(6)
print cols4
count=1
#從姓名列一個一個處理
for name in cols4:
print ""
print str(count)+" "+name
index = cols4.index(name)
print name + " select "+sheet1.cell(index,4).value.encode('utf-8')\
+"? "+sheet1.cell(index,5).value.encode('utf-8')\
+"? "+sheet1.cell(index,6).value.encode('utf-8')
count = count + 1
row = sheet1.row_values(cols4.index(name))? ? ? ? ? ? ? ? ? ? ? #取出自己所在的整列元素
if name in cols5 and name != u'':
a = sheet1.cell(cols5.index(name),3).value? ? ? ? ? ? ? ? ? ? ? #找到誰把你選為了五星
print "and " +a.encode('utf-8')+" select "+name
if a in row:
print a+" and "+name+" select each other!!!!!!!!!!!!!!!!!"
if name in cols6 and name != u'':
a = sheet1.cell(cols6.index(name),3).value? ? ? ? ? ? ? ? ? ? ? #找到誰把你選為了四星
print "and " +a.encode('utf-8')+" select "+name
if a in row:
print a+" and "+name+" select each other!!!!!!!!!!!!!!!!!"
if name in cols7 and name != u'':
a = sheet1.cell(cols7.index(name),3).value? ? ? ? ? ? ? ? ? ? ? #找到誰把你選為了三星
print "and " +a.encode('utf-8')+" select "+name
if a in row:
print a+" and "+name+" select each other!!!!!!!!!!!!!!!!!!"
# print rows[0].encode('utf-8'),rows[1].encode('utf-8')
# 獲取單元格內容
#print sheet1.cell(1,0).value.encode('utf-8')
#print sheet1.cell_value(1,0).encode('utf-8')
#print sheet1.row(1)[0].value.encode('utf-8')
# 獲取單元格內容的數(shù)據(jù)類型
#print sheet1.cell(1,0).ctype
if __name__ == '__main__':
#edit_and_sava_as_excel()
read_excel()
'''