在Python中调用Excel文档,你可以使用以下几种方法:
1. 使用`pandas`库
```python
import pandas as pd
读取Excel文件
df = pd.read_excel('example.xlsx')
显示前几行数据
print(df.head())
2. 使用`openpyxl`库
```python
from openpyxl import load_workbook
加载Excel文件
wb = load_workbook('example.xlsx')
选择工作表
sheet = wb.active
读取特定单元格的数据
cell_value = sheet['A1'].value
print(cell_value)
3. 使用`xlrd`库
```python
import xlrd
打开Excel文档
workbook = xlrd.open_workbook('test_case.xlsx')
获取所有的sheet表
sheet_names = workbook.sheet_names()
获取指定的sheet表
sheet = workbook.sheet_by_name('Sheet1')
获取指定sheet的名字、行数、列数
print(sheet.name, sheet.nrows, sheet.ncols)
获取sheet的内容
for row_idx in range(sheet.nrows):
for col_idx in range(sheet.ncols):
print(sheet.cell_value(row_idx, col_idx))
4. 使用VBA调用Python脚本
在Excel中准备调用的Python代码,例如:
```python
def merge_sort_unique(lists):
s = set()
for L in lists:
s.update(L)
return sorted(s)
在Excel的VBA编辑器中,使用`PyModule`函数调用Python脚本。
以上方法可以帮助你在Python中读取和操作Excel文档。请根据你的具体需求选择合适的方法