Python 使用xlwt xlrd 读写表格数据

1、安装相关包

pip install xlrd xlwt

2、使用xlwt写表格数据

import xlwt


def main():
    init_data1 = {
    
    
        "姓名": ['张三', '李四', '王五', '王二'], 
        "年龄": [23, 22,12,43], 
    }
    book = xlwt.Workbook(encoding="utf-8",style_compression=0)
    sheet1 = book.add_sheet('sheet1', cell_overwrite_ok=True)
    for index, item in enumerate(init_data1):
        # 先写表的标题
        sheet1.write(0, index, item) # write写数据的方法,参数是行索引、列索引、数据
        sheet1.col(index).width = 300 * 40 # 设置该单元格的大小
        for i in range(1,len(init_data1[item]) + 1):
            sheet1.write(i, index, init_data1[item][i-1]) # 写入列表中的数据
    book.save('save.xls')


if __name__ == '__main__':
    main()

3、使用xlrd读取表格数据

import xlrd
import os

base_dir = os.path.dirname(os.path.abspath(__file__))


def main():
    xls_path = os.path.join(base_dir, 'save.xls')
    # 创建读取表格的对象
    workbook=xlrd.open_workbook(xls_path)
    #获取所有sheet的名字
    names = workbook.sheet_names()
    print(names) #['sheet1', 'sheet2']  输出所有的表名,以列表的形式
    #通过sheet名获得sheet对象
    worksheet = workbook.sheet_by_name(names[0])
    '''
    对sheet对象进行操作
    '''
    # 获取表的名称
    name = worksheet.name 
    print(name)
    # 获取该表总行数
    nrows = worksheet.nrows
    print('行数:%d' % nrows)
    # 获取该表总列数
    ncols = worksheet.ncols
    print('列数:%d' % ncols)
    '''
    读取表格中数据
    '''
    # 循环打印每一行
    for i in range(nrows): 
        # row_values(num) 获取某一行的数据
        print(worksheet.row_values(i))  
    
    # 获取最后一列的内容 col_values(num) 获取某一列的数据
    col_data=worksheet.col_values(ncols - 1)
    print(col_data)


if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/haeasringnar/article/details/110331205