1、读取操作步骤:
(1)导入模块xlrd
(2)打开工作薄Book
(3)指定工作薄中的表单sheet
(4)根据行列号读取内容
#(1)导入模块xlrd
import xlrd
#如果没安装,需要使用 pip install xlrd
#(2)打开工作薄Book
wb = xlrd.open_workbook('../Stu_pack/school.xls')
#(3)指定工作薄中的工作表sheet
sheet = wb.sheet_by_index(0) #索引第一个工作表
#(4)根据行列号读取内容
schools = [] #定义一个二维列表schools
for row in range(sheet.nrows):#以文件schools遍历
school = []#定义一个一维列表
for col in range(sheet.ncols):
content = sheet.cell_value(row,col)#读取单元格内容并保存在变量content里面
school.append(content)#将从单元格读取的内容追加到一维列表school中
schools.append(school)#将读取的一行内容追加到二维列表schools中
#i=1
for school in schools:#读取文件的内容
#if i <12:
print(school)
#i+=1
2、Excel文件的写入操作步骤:
(1)导入模块:xlwt
(2)构造工作薄:Workbook
(3)为工作薄添加表单:Worksheet
(4)根据行列序号写入内容
(5)保存文件
(1)导入模块:xlwt
import xlwt
import xlrd
def read_excel(file_name): #定义读取文件函数
wb = xlrd.open_workbook(file_name)
#(3)指定工作薄中的工作表sheet
sheet = wb.sheet_by_index(0) #索引第一个工作表
#(4)根据行列号读取内容
schools = [] #定义一个二维列表schools
for row in range(sheet.nrows):#以文件schools遍历
school = []#定义一个一维列表
for col in range(sheet.ncols):
content = sheet.cell_value(row,col)#读取单元格内容并保存在变量content里面
school.append(content)#将从单元格读取的内容追加到一维列表school中
schools.append(school)#将读取的一行内容追加到二维列表schools中
return schools
def write_excel(schools): #定义写入函数
wb = xlwt.Workbook(encoding = 'utf-8')
sheet = wb.add_sheet('上海市高校信息表') #创建一个工作表
sheet.write_merge(0,0,0,6,'上海高校信息表')#写标题并且合并单元格(A1:G1)
for col in range(7):
sheet.write(1,col,schools[0][col])#第2行第1列开始写内容
row_num = 2 #从第三行开始写数据
for school in schools:
if school[2] == '上海市':
for col in range(7):
sheet.write(row_num,col,school[col])
row_num = row_num+1 #行数增加1
wb.save('../R&Q_pic/上海市高校信息表.xls')
#(5)函数的调用
school_list = read_excel('../Stu_pack/school.xls')
write_excel(school_list)
school_list = read_excel('../R&Q_pic/上海市高校信息表.xls')
for school in school_list:
print(school)
最后运行测试