python 在一个excel多次创建sheet,记录数据
时间: 2023-05-04 18:04:14 浏览: 107
在Python中,我们可以使用第三方库openpyxl来操作Excel文件。要在一个Excel文件中多次创建sheet并记录数据,可以按以下步骤进行:
1. 导入openpyxl库
```python
import openpyxl
```
2. 打开Excel文件
```python
wb = openpyxl.load_workbook('example.xlsx')
```
3. 创建sheet,并记录数据
```python
# 创建一个名为Sheet1的sheet,并将数据写入
sheet1 = wb.create_sheet('Sheet1')
sheet1['A1'] = 'Hello'
sheet1['B1'] = 'World'
# 创建一个名为Sheet2的sheet,并将数据写入
sheet2 = wb.create_sheet('Sheet2')
sheet2['A1'] = 'Python'
sheet2['B1'] = 'Excel'
```
4. 保存Excel文件
```python
wb.save('example.xlsx')
```
完整代码如下:
```python
import openpyxl
# 打开Excel文件
wb = openpyxl.load_workbook('example.xlsx')
# 创建一个名为Sheet1的sheet,并将数据写入
sheet1 = wb.create_sheet('Sheet1')
sheet1['A1'] = 'Hello'
sheet1['B1'] = 'World'
# 创建一个名为Sheet2的sheet,并将数据写入
sheet2 = wb.create_sheet('Sheet2')
sheet2['A1'] = 'Python'
sheet2['B1'] = 'Excel'
# 保存Excel文件
wb.save('example.xlsx')
```
以上代码创建了一个名为example.xlsx的Excel文件,并在其中创建了两个sheet,分别为Sheet1和Sheet2,并在每个sheet的A1和B1单元格中记录了数据。如果需要在之后的时候继续向这些sheet中添加数据,可以使用openpyxl库提供的相关方法进行操作。
阅读全文
相关推荐


















