python

xlrd模块:只能读xls文件
  data = xlrd.open_workbook('excelFile.xls') 打开excel文件
  获取表
    r_sheet = data.sheet_names()          获取所有的表名
    table = data.sheets()[0]             通过索引获取表
    table = data.sheet_by_index(0)         通过索引获取表
    table = data.sheet_by_name(u'Sheet1')     通过表名获取表
    
  获取数值
    table.row_values(i)                获取整行的值
    table.col_values(i)                获取整列的值
  
    nrows = table.nrows                获取行数
    ncols = table.ncols                获取列数
    cell_A1 = table.cell(0,0).value         获取单元格的值
    cell_A1 = table.cell_value(0, 0)         获取单元格的值
    cell_A1 = table.row(0)[0].value         使用行索引获取单元格值
    cell_A2 = table.col(1)[0].value         使用列索引获取单元格值

xlwt模块:只写xls文件
    excel = xlwt.Workbook()              初始化一个excel文件
    sheet = excel.add_sheet()             新加一个sheet表
    sheet.write(0,0,value)               写入数据
    excel.save(path)                     保存excel文件
xlutils模块:可以修改excel文件
    from xlutils improt copy
    book1 = xlrd.open_workbook(file)
    book2 = copy.(book1)              拷贝原来的一份excel
    sheet = book2.get_sheet(i)          通过索引获取表
    sheet.write(0,0,value)             写入数据
    sheet.save(file)               保存


openpyxl模块:可以操作xlsx 2016
    读改
    from openpyxl import load_workbook      读取已有文件
    excel=load_workbook('E:/test.xlsx')     打开文件
    
    table = excel.active或excel.get_active_sheet() 获取默认表
    table = get_sheet_names()            获得所有sheet的名称
    table = excel.get_sheet_by_name('Sheet1')  根据表名获取表
    sheet.title                    获取sheet名    
    ws1 = wb.create_sheet()             创建sheet
    ws2 = wb.create_sheet(0)             插在0前创建

    rows=table.max_row                获取行数
    cols=table.max_column              获取列数
    
    b4 = sheet['B4']                 获取某个单元格的值,观察excel发现也是先字母再数字的顺序,即先列再行
    Data=table.cell(row=row,column=col).value  获取单元格值
    
    from openpyxl.utils import get_column_letter, column_index_from_string
    get_column_letter(2) # B            根据列的数字返回字母
    column_index_from_string('D')         根据字母返回列的数字

    写入文件
    from openpyxl import Workbook
    wb = Workbook()                 新建了一个新的工作表(只是还没被保存)

    sheet.cell(row=2,column=5).value=99     写入数据 (row,column 是从1,1 开始)
    sheet.cell(row=3,column=5,value=100)     写入数据
    
     ws.append([‘This is A1’, ‘This is B1’, ‘This is C1’])    逐行添加
     ws.append({‘A’ : ‘This is A1’, ‘C’ : ‘This is C1’})
     ws.append({1 : ‘This is A1’, 3 : ‘This is C1’})
原文地址:https://www.cnblogs.com/pengranxindong/p/9934095.html