# Python操作excel主要用到xlrd和xlwt这两个库 # 即xlrd是读excel,xlwt是写excel的库 # xl是excel的缩写,rd是read,wt是write # xlrd可以解析微软的.xls and .xlsx两种各种的电子表格 # xlrd的使用 # 导入工具包 import xlrd # # 1. 打开表格 rd = xlrd.open_workbook("config/user_info.xls",'r', encoding_override="UTF-8") # # 2. 获取表格的sheets rd_nsheets_num = rd.nsheets print("rd_nsheets_num>>>>", rd_nsheets_num) # 3. 获取sheets名字 sheet_names = rd.sheet_names() print("sheet_names>>>>", type(sheet_names), sheet_names) # 4. 获取单个sheet行,列总数 rd_sheet_rows = rd.sheet_by_index(0).nrows print("rd_sheet_rows>>>>", rd_sheet_rows) rd_sheet_cols = rd.sheet_by_index(0).ncols print("rd_sheet_cols>>>>", rd_sheet_cols) # 5. 获取每一行内容 rd_sheet_rows_context = rd.sheet_by_index(0).row(0) print("rd_sheet_rows_context>>>>", rd_sheet_rows_context) # 6. 获取每一列内容 rd_sheet_cols_context = rd.sheet_by_index(0).col(1) print("rd_sheet_cols_context>>>>", rd_sheet_cols_context) # 7. 获取单元格内容 rd_sheet_cell = rd.sheet_by_index(0).cell(0,1) print("rd_sheet_cell>>>>", rd_sheet_cell) # xlwt的使用 import xlwt # 1. 建表,创建 一个wbook对象 wbook = xlwt.Workbook("config/user_info_001.xls","w+b") # 2. 增加sheet wsheet = wbook.add_sheet("person_age2") # 3. 一行一行写入内容 person_name = ["person_name","lisa001","lisa002","lisa003","lisa004"] person_age = ["person_age",12,34,45,67] for i in range(len(person_name)): for j in range(0,1): wsheet.write(i, j, person_name[i]) wsheet.write(i, j + 1, person_age[i]) # 4. 生成excel文件 wbook.save("config/user_info_001.xls")
python文件处理之EXCEL
最新推荐文章于 2022-11-26 17:31:49 发布