情境:读取Excel自动处理时,往往会在数据后面加一个处理标识,记录以处理数据与未处理数据
import xlrd
import xlwt
def read_excel(fname,sheetname):
book = xlrd.open_workbook(fname)
sheet = book.sheet_by_name(sheetname)
# 获取行数
nrows = sheet.nrows
row_list = []
# 获取各行数据
for i in range(1, nrows):
row_data = sheet.row_values(i)
row_list.append(row_data)
return row_list
def write_excel(datas,filename):
book = xlwt.Workbook()
sheet1 = book.add_sheet('Sheet1')
for x,data in enumerate(datas):
print(data)
for y,param in enumerate(data):
if y == 2:
sheet1.write(x,y,'True')
else:
sheet1.write(x,y,param)
book.save(filename)
print(read_excel('demo.xls','Sheet1'))
datas = read_excel('demo.xls','Sheet1')
from xlutils.copy import copy
def write_exist_excel(filename,sheetname):
#读取旧Excel中的信息
exist_excel = xlrd.open_workbook(filename)
sheet = exist_excel.sheet_by_name(sheetname)
nrows = sheet.nrows
#复制已存在的Excel
new_excel = copy(exist_excel)
new_sheet = new_excel.get_sheet(sheetname)
for i in range(1,nrows):
row_data = sheet.row_values(i)
print(row_data)
# 在新的Excel中写入
new_sheet.write(i,2,'True')
new_excel.save(filename)
write_exist_excel('demo.xls','Sheet1')