Home  >  Article  >  Backend Development  >  What is the basic method of operating Excel in Python?

What is the basic method of operating Excel in Python?

WBOY
WBOYforward
2023-05-11 11:04:081609browse

    Write to Excel

    1. Install third-party module

    You can use it to modify excelxlwtmodule

    pip install xlwt=1.2.0

    2. Write code

    • ##xlwt.Workbook method to create an Excel file

    • work_book.add_sheet: Add a table

    • work_sheet.write: Write data (rows, columns, data) into the table

    • work_book.save:Save the file

    • import xlwt
      # 创建一个Excel文件,字符编码为utf-8
      work_book = xlwt.Workbook(encoding='utf-8')
      # 添加一张表,名字为测试表
      work_sheet = work_book.add_sheet('测试表')
      # 往表中写入值(行,列,数据)
      work_sheet.write(0, 0, label='姓名')
      work_sheet.write(1, 0, label='李四')
      # 保存
      work_book.save('student.xls')
    Read Excel

    1. Install third-party modules

    You can use the

    xlrd module to read Excel

    pip install xlrd==1.2.0

    2. Write code

    This is a table named student.xls under the D drive

    What is the basic method of operating Excel in Python?

    • ##xlrd.open_workbook

      Method used to open an Excel file

      ##Use
    • xlsx_file.sheet_by_index
    • Method to get to tab page 0

      ##table.nrows
    • Get the total number of rows
    • table.cell_value
    • Get the value of the specified (row, column) in the table
    • # 打开Excel文件
      xlsx_file = xlrd.open_workbook('D:/student.xls')
      # 获取第0号标签页(也可以通过表名获取)
      table = xlsx_file.sheet_by_index(0)
      # table = xlsx_file.sheet_by_name('Sheet1')
      # 获取表格的总行数
      rows = table.nrows
      # 遍历每一行数据
      for i in range(1, rows):
          name = table.cell_value(i, 0)
          sex = table.cell_value(i, 1)
          age = table.cell_value(i, 2)
          print(f'name:{name}\tsex={sex}\tage={age}')
      # 运行结果
      name:张三	sex=男	age=18.0
      name:李四	sex=女	age=20.0

    The above is the detailed content of What is the basic method of operating Excel in Python?. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete