Python读取Excel数据代码
时间: 2024-01-10 22:05:31 浏览: 84
使用Python读取Excel数据需要用到第三方库,常用的有xlrd、openpyxl和pandas等。以下是使用xlrd库读取Excel数据的示例代码:
```python
import xlrd
# 打开Excel文件
workbook = xlrd.open_workbook('example.xlsx')
# 获取所有sheet名称
sheet_names = workbook.sheet_names()
print(sheet_names)
# 根据sheet索引或名称获取sheet内容
sheet1 = workbook.sheet_by_index(0)
sheet2 = workbook.sheet_by_name('Sheet2')
# 获取sheet的行数和列数
num_rows = sheet1.nrows
num_cols = sheet1.ncols
# 遍历每一行数据
for i in range(num_rows):
row_values = sheet1.row_values(i)
print(row_values)
```
使用openpyxl库读取Excel数据的示例代码:
```python
from openpyxl import load_workbook
# 打开Excel文件
workbook = load_workbook(filename='example.xlsx')
# 获取所有sheet名称
sheet_names = workbook.sheetnames
print(sheet_names)
# 根据sheet名称获取sheet内容
sheet1 = workbook['Sheet1']
sheet2 = workbook['Sheet2']
# 获取sheet的行数和列数
num_rows = sheet1.max_row
num_cols = sheet1.max_column
# 遍历每一行数据
for row in sheet1.iter_rows(min_row=1, max_row=num_rows, values_only=True):
print(row)
```
使用pandas库读取Excel数据的示例代码:
```python
import pandas as pd
# 读取Excel文件中的Sheet1
df = pd.read_excel('example.xlsx', sheet_name='Sheet1')
# 获取所有行和列
rows, cols = df.shape
# 遍历每一行数据
for i in range(rows):
row_values = df.loc[i].values.tolist()
print(row_values)
```
阅读全文