import xlwt import xlrd from xlutils.copy import copy import random import openpyxl
#下面为从xls文件读取数据,写入读取记录 def xls_words(): #fn=u'D:/2018熊/伊学专栏/背单词方法/初一单词.xlsx' #两种文件xlrd都可以读,xlwt只能写xls fn='C:/Users/Administrator/Desktop/sms/1234.xls' xls=xlrd.open_workbook(filename=fn)#打开电子表格文件 sheet1=xls.sheet_by_index(0)#打开第一个sheet n=sheet1.nrows#取出总行数 a=sheet1.row_values(0)[0]#xlrd库从0,0开始取值 print(a) ##sheet1.put_cell(2,4,2,a+1,0)#不能写加文件 #写操作 xls_copy=copy(xls) sheet_w=xls_copy.get_sheet(0) words='' for r in random.sample(range(1,n-1),30):#不重复随机数 #r=random.randint(1,n-1) #产生随机数,第0行标题,末行n-1 words+=sheet1.row_values(r)[0]+'\t'+sheet1.row_values(r)[1]+'\n' record=sheet1.row_values(r)[2] sheet_w.write(r,2,record+1) xls_copy.save(fn) print(words)
#下面为从xlsx电子表格随机取出一行数据,并添加一次操作记录。 def xlsx_words(): #fn=u'D:/2018熊/伊学专栏/背单词方法/初一单词.xlsx' fn='C:/Users/Administrator/Desktop/sms/12345.xlsx' #xls=xlrd.open_workbook(filename=fn)#打开电子表格文件 #sheet1=xls.sheet_by_index(0)#打开第一个sheet #n=sheet1.nrows xlsx=openpyxl.load_workbook(fn)#打开xlsx文件 sheet1=xlsx.worksheets[0]#打开第一个sheet n=sheet1.max_row#读取总行数 words='' for r in random.sample(range(2,n),30):#sample 没有重复数 #r=random.randint(2,n)#产生随机数,第一行标题 #words+=sheet1.row_values(r)[0]+'\t'+sheet1.row_values(r)[1]+'\t'\ #+sheet1.row_values(r)[2]+'\t'+sheet1.row_values(r)[3]+'\n' words+=sheet1.cell(r,1).value+'\t'+sheet1.cell(r,2).value+'\t'\ +sheet1.cell(r,3).value+'\t'+sheet1.cell(r,4).value+'\n' record=sheet1.cell(r,5).value #openpyxl库从1,1开始。注意 sheet1.cell(r,5).value=record+1 xlsx.save(fn) #return words
xls_words() xlsx_words()
#import openpyxl ###这个openpyxl不支持xls,么家伙 ##xlsx=openpyxl.load_workbook(fn) ##sheet1=xlsx.worksheets[0] ##n=sheet1.max_row ###取出一行的值很麻烦,生成器 ##a=sheet1.rows#所有行<class 'generator'> ##b=list(a)#转为列表 ##c=b[2]#元组类型#取出第几行 ###不能直接取出,需要下面迭代 ##for i in c: ## print(i.value) ##a=sheet1.cell(2,5).value #openpyxl库从1,1开始。注意 ##print(type(a)) ##sheet1.cell(2,5).value=a+1 ##xlsx.save(fn)