Python表格文件操作xlrd&xlwt&xlutils

101 阅读1分钟

表格文件操作

xlrd读取表格

对表格文件进行读取

  • 打开文件
import xlrd
execl  = xlrd.open_workbook('path')
  • 获取文件中所有工作表的名称
execl.sheet_names()
  • 选择某个工作表
sheet = execl.sheet_by_name('sheet_name') # 通过名称
sheet = execl.sheet_by_index('sheet_index') # 通过名字
  • 查看工作表的行数
rowNum = sheet.nrows
  • 查看工作表的列数
colNum = sheet.ncols
  • 获取一行或一列上的内容
sheet.row_values(num)
sheet.col_values(num)
  • 获取某个单元格
data = sheet.cell(rowx, colx)
# 单元格属性获取
data.value # 单元格的值
data.ctype # 单元格值类型 
'''
0:empty、1:string、2:number、4:boolean
3:date、5:error 
'''
  • 一个demo
import xlrd
execl = xlrd.open_workbook('/Users/lienze/Desktop/1.xlsx')
execl_names = execl.sheet_names() # 查看sheet的名字
sheet = execl.sheet_by_index(0) # 选择第一个sheet
#-----------遍历整个列表读取数据----------
for row in range(sheet.nrows):
    for col in range(sheet.ncols):
        data = sheet.cell(row,col)
        print(data.value,end='\t|')
    print('\v')

xlwt写入表格

对表格文件进行写入

  • 初始化操作句柄
import xlwt
workbook = xlwt.Workbook(encoding = 'utf-8') # 创建一个workbook 设置编码
  • 添加sheet
worksheet = workbook.add_sheet('My Worksheet') # 添加一个sheet
  • 写入数据
worksheet.write(1,0, label = 'this is test') # 表格指定位置写入数据
  • 保存
workbook.save('Excel_test.xls')

xlutils拷贝表格

  • 如果需要操作已有表格,那么需要进行拷贝,安装一个新的模块
pip install xlutils
  • 拷贝表格并且修改
from xlutils.copy import copy  
import xlrd  
import xlwt  
old_excel = xlrd.open_workbook('fileName.xls')  # 打开历史文件
new_excel = copy(old_excel)  # 拷贝为新的表格文件
ws = new_excel.get_sheet(0) # 获取对应sheet
ws.write(row, col, label='修改内容') # 修改
new_excel.save()