Excel文件的读取与写入
1、读取操作步骤:
(1)导入模块xlrd
(2)打开工作簿Book
(3)指定工作簿中的表单Sheet
(4)根据行列序号读取内容
如:
#实例:读取Stu_pack的Excel文件内容school.xls,将结果保存以列表中 #(1)导入模块xlrd import xlrd #(2)打开工作簿Book wb = xlrd.open_workbook('../Stu_pack/school.xls') #(3)指定工作簿中的工作表Sheet sheet = wb.sheet_by_index(0) #(4)根据行列序号读取内容 schools = [] #定义一个二维列表 for row in range(sheet.nrows): school = [] #定义一个一维列表存放单元格内容 for col in range(sheet.ncols): content = sheet.cell_value(row,col) school.append(content) #将单元格内容追加到一维列表里面 schools.append(school) #将每行的内容追加到二维列表里面
从列表中读取数据
i=1 for school in schools: if i<12: print(school) i=i+1
输出为:
2、Excel文件的写入操作步骤:
(1)导入模块:xlwt
(2)构造工作簿:Workbook
(3)为工作簿添加表单:Worksheet
(4)根据行列序号写入内容
(5)保存文件
#(1)导入模块:xlwt和xlrd import xlrd import xlwt
#2、读取文件内容 def read_excel(file_name): wb = xlrd.open_workbook(file_name) sheet = wb.sheet_by_index(0) schools = [] #定义一个二维列表 for row in range(sheet.nrows): school = [] #定义一个一维列表存放单元格内容 for col in range(sheet.ncols): content = sheet.cell_value(row,col) school.append(content) #将单元格内容追加到一维列表里面 schools.append(school) #将每行的内容追加到二维列表里面 return schools #返回二维列表值
#3、导入文件内容 def write_excel(schools): #(2)构造工作簿:Workbook wb = xlwt.Workbook(encoding = 'utf-8') #(3)为工作簿添加表单:Worksheet sheet = wb.add_sheet('上海市高校信息表') #(4)根据行列序号写入内容 sheet.write_merge(0,0,0,6,'上海市高校信息表') #合并第一行第一个单元格到第六个单元格写入表头 for col in range(7): #写入列表名称(列表字段) sheet.write(1,col,schools[0][col]) 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行 #(5)保存文件 wb.save('../R&Q_pic/上海市高校信息表.xls')
#调用函数: schools = read_excel('../R&Q_pic/上海市高校信息表.xls') write_excel(schools) i=1 for school in schools: if i<12: print(school) i=i+1
输出为: