Python办公自动化 | excel读取和写入

    技术2025-04-13  32

    python在办公自动化领域应用广泛,本文学习一下如何使用python读取和写入excel。EXCEL读取和写入可以用到两个包:xlrd 和 xlwt。

    Excel读取

    excel几个基本概念: 工作簿就是指这个excel文件 工作表就是excel文件中的不同sheet 单元格就是某个sheet中的某个位置

    首先在cmd命令行安装 xlrd 包

    pip install xlrd

    安装后咱们开始编写代码

    首先导入xlrd包

    import xlrd

    打开工作簿

    xlsx = xlrd.open_workbook(r'D:\pycharm\learning\autowork\test.xlsx')

    打开工作表,这里提供两种方法,可以通过索引或者sheet的名称

    使用索引(行和列的索引都是0开始)

    table = xlsx.sheet_by_index(0)

    使用名称

    table = xlsx.sheet_by_name('sheet1')

    打印单元格,这里提供三种方法

    print(table.cell_value(0, 0)) print(table.cell(0, 0).value) print(table.row(0)[0].value)

    Excel写入

    首先在cmd命令行安装 xlwt 包

    pip install xlwt

    新建工作簿

    new_workbook = xlwt.Workbook()

    新建工作表

    new_sheet = new_workbook.add_sheet('aaa')

    写入内容

    new_sheet.write(1, 1, 'hello word')

    保存工作簿(注意保存2003格式)

    new_workbook.save(r'D:\pycharm\learning\autowork\test2.xls')

    至此,便新建了一个文件 test2,打开该文件看到 hello world 成功写入到1行1列的单元格

    总结

    完整代码如下

    import xlrd import xlwt xlsx = xlrd.open_workbook(r'D:\pycharm\learning\autowork\test.xlsx') table = xlsx.sheet_by_index(0) # table = xlsx.sheet_by_name('Sheet1') print(table.cell_value(0, 0)) print(table.cell(0, 0).value) print(table.row(0)[0].value) new_workbook = xlwt.Workbook() new_sheet = new_workbook.add_sheet('aaa') new_sheet.write(1, 1, 'hello word') new_workbook.save(r'D:\pycharm\learning\autowork\test2.xls')
    Processed: 0.010, SQL: 9