python简单操作excel
python操作excel
-
写入excel
# 写入excel import xlwt # 创建xls对象 wb = xlwt.Workbook() # 新增两个表单页(sheet1) sh1 = wb.add_sheet("成绩") # 按照位置添加数据 第一个参数是行,第二个参数是列(行和列的默认下标均从0开始) # 写入第一个sheet sh1.write(0, 0, "姓名") sh1.write(0, 1, "成绩") sh1.write(1, 0, "张三") sh1.write(1, 1, "88") # 保存到文件 wb.save('test_x.xls')
-
从excel读取文件
# 从xls里面读取数据 import xlrd # 打开刚才的excel文件 wb = xlrd.open_workbook("test_x.xls") # 获取并打印sheet数量 print("sheet数量:", wb.nsheets) # 获取并打印 sheet 名称 print("sheet 名称:", wb.sheet_names()) # 根据sheet索引获取内容 sh1 = wb.sheet_by_index(0) # 根据sheet名称获取 # sh11=wb.sheet_by_name("成绩") # 获取该sheet的行数和列数 print(u"sheet %s 共 %d 行 %d 列" % (sh1.name, sh1.nrows, sh1.ncols)) # 获取并打印某个单元格的值 print("第一行第二列的值为:", sh1.cell_value(0, 1)) # 获取整行或整列的值 rows = sh1.row_values(0) # 获取第一行内容 cols = sh1.col_values(1) # 获取第二列内容 # 打印获取的行列值 print("第一行的值为:", rows) print("第二列的值为:", cols) # 遍历所有表单内容 for sh in wb.sheets(): for r in range(sh.nrows): # 输出指定行 print(sh.row(r))
-
修改excel
# 导入相应模块 import xlrd from xlutils.copy import copy # 打开 excel 文件 readbook = xlrd.open_workbook("test_x.xls") # 复制一份 wb = copy(readbook) # 选取第一个表单 sh1 = wb.get_sheet(0) # 在第四行新增写入数据 sh1.write(2, 0, '王亮') sh1.write(2, 1, "59") # 保存 wb.save('test_x.xls')