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

What is the basic method of operating Excel in Python?

WBOY
Release: 2023-05-11 11:04:08
forward
1727 people have browsed it

    Write to Excel

    1. Install third-party module

    You can use it to modify excelxlwtmodule

    pip install xlwt=1.2.0
    Copy after login

    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')
      Copy after login
    Read Excel

    1. Install third-party modules

    You can use the

    xlrd module to read Excel

    pip install xlrd==1.2.0
    Copy after login

    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
      Copy after login

    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!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template