Home  >  Article  >  Backend Development  >  How to read excel in python

How to read excel in python

(*-*)浩
(*-*)浩Original
2019-07-02 10:54:135369browse

Python uses openpyxl to read and write excel files

This is a third-party library that can handle Excel files in xlsx format. pip install openpyxl installation. If you use Aanconda, it should come with it.

How to read excel in python

Reading Excel files (Recommended learning: Python video tutorial)

Need to import related functions.

from openpyxl import load_workbook
# 默认可读写,若有需要可以指定write_only和read_only为True
wb = load_workbook('mainbuilding33.xlsx')

The file opened by default is readable and writable. If necessary, you can specify the parameter read_only as True.

Get the worksheet--Sheet

# 获得所有sheet的名称
print(wb.get_sheet_names())
# 根据sheet名字获得sheet
a_sheet = wb.get_sheet_by_name('Sheet1')
# 获得sheet名
print(a_sheet.title)
# 获得当前正在显示的sheet, 也可以用wb.get_active_sheet()
sheet = wb.active

Get the cell

# 获取某个单元格的值,观察excel发现也是先字母再数字的顺序,即先列再行
b4 = sheet['B4']
# 分别返回
print(f'({b4.column}, {b4.row}) is {b4.value}') # 返回的数字就是int型
# 除了用下标的方式获得,还可以用cell函数, 换成数字,这个表示B4
b4_too = sheet.cell(row=4, column=2)
print(b4_too.value)

b4.column returns B, b4.row Returns 4, value is the value of that cell. In addition, cell also has an attribute coordinate. Cells like b4 return coordinate B4.

For more Python related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to read excel in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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