python操作excel数据表
时间: 2023-12-20 13:32:42 浏览: 81
以下是使用xlrd库和xlwt库进行Python操作Excel数据表的示例:
1. 使用xlrd库读取Excel数据表:
```python
import xlrd
# 打开Excel文件
workbook = xlrd.open_workbook('E:\Code\Python\testdata.xls')
# 获取所有的sheet名称
sheet_names = workbook.sheet_names()
print("Sheet Names:", sheet_names)
# 获取第一个sheet对象
sheet = workbook.sheet_by_index(0)
# 获取行数和列数
num_rows = sheet.nrows
num_cols = sheet.ncols
print("Number of rows:", num_rows)
print("Number of columns:", num_cols)
# 遍历每一行,获取数据
for row in range(num_rows):
row_data = sheet.row_values(row)
print("Row", row+1, ":", row_data)
# 获取指定单元格的数据
cell_value = sheet.cell_value(1, 1)
print("Cell B2 value:", cell_value)
```
2. 使用xlwt库写入Excel数据表:
```python
import xlwt
# 创建一个新的Excel文件
workbook = xlwt.Workbook()
# 创建一个sheet对象
sheet = workbook.add_sheet('Sheet1')
# 写入数据
sheet.write(0, 0, 'Name')
sheet.write(0, 1, 'Age')
sheet.write(1, 0, 'John')
sheet.write(1, 1, 25)
sheet.write(2, 0, 'Alice')
sheet.write(2, 1, 30)
# 保存Excel文件
workbook.save('E:\Code\Python\output.xls')
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)