2022/03/01,三月的第一天,学习了Python读取Excel数据的两种方法;Python将Excel的数据存入列表中;求列表的最大值
import pandas as pd custom_data = pd.read_excel(r'D:\python_resource\001analy_base\foundations-for-analytics-with-python-master\applications\historical_files\suppliers.xlsx', sheet_name='suppliers_2013') print(custom_data)
输出结果
注:excel文件要和程序保存在一个目录下
import xlrd import xlwt def read_excel(): #打开文件 workExcel = xlrd.open_workbook('suppliers.xlsx') #获取所有sheet的名字 allSheet = workExcel.sheet_names() print(allSheet) #按索引号获取sheet的名字(string)类型 sheetName = workExcel.sheet_names()[0] print(sheetName) #获取sheet内容 sheet1 = workExcel.sheet_by_index(0) sheet2 = workExcel.sheet_by_name('suppliers_2014') #输出sheet1的名称,行数、列数 print("sheet名称: "+sheet1.name," 行数"+str(sheet1.nrows)," 行数:"+str(sheet1.ncols)) print("sheet名称: "+sheet2.name," 行数"+str(sheet2.nrows)," 行数:"+str(sheet2.ncols)) #获取整行整列的值: row3 = sheet1.row_values(3) col2 = sheet1.col_values(2) print(row3,col2) #获取单元格数据 print(sheet1.cell(1,0).value) print(sheet1.cell_value(1,3)) if __name__ == '__main__': read_excel();
对存入列表中的值操作,值不是空的存入列表,值为空的默认为0值
import xlrd import xlwt def read_excel(): #打开文件 workExcel = xlrd.open_workbook('suppliers.xlsx') workExcel_1 = workExcel.sheet_by_index(0) excel_list_1 = [] #定义一个空列表,将数据存入该列表中 for i in range(1,workExcel_1.nrows): #将excel的第一列存入列表中,值不是空的存入列表,值为空的默认为0值 if workExcel_1.cell_value(i,0) is not '': excel_list_1.append(workExcel_1.cell_value(i,0)) else: excel_list_1.append(0) print(excel_list_1) if __name__ == '__main__': read_excel();
for循环实现
import xlrd import xlwt def read_excel(): #打开文件 workExcel = xlrd.open_workbook('suppliers.xlsx') workExcel_1 = workExcel.sheet_by_index(0) excel_list_1 = [] #定义一个空列表,将数据存入该列表中 for i in range(1,workExcel_1.nrows): #将excel的第一列存入列表中,值不是空的存入列表,值为空的默认为0值 if workExcel_1.cell_value(i,0) is not '': excel_list_1.append(workExcel_1.cell_value(i,0)) else: excel_list_1.append(0) print(excel_list_1) for j in range(len(excel_list_1)-1): if(int(excel_list_1[j+1])>int(excel_list_1[j])): value_max = int(excel_list_1[j+1]) print("最大值是:") print(value_max) if __name__ == '__main__': read_excel();