Python 把内容分别写到EXCEL多个sheet
时间: 2024-03-21 08:07:57 浏览: 20
可以使用Python的第三方库xlwt或openpyxl来实现将内容分别写入到Excel的多个sheet中。
使用xlwt库的示例代码如下:
```python
import xlwt
# 创建一个Workbook对象,即相当于创建了一个Excel文件
workbook = xlwt.Workbook()
# 创建sheet并命名
sheet1 = workbook.add_sheet('Sheet1')
sheet2 = workbook.add_sheet('Sheet2')
# 写入数据到sheet1
sheet1.write(0, 0, 'Hello')
sheet1.write(0, 1, 'World')
# 写入数据到sheet2
sheet2.write(0, 0, 'Python')
sheet2.write(0, 1, 'Excel')
# 保存Excel文件
workbook.save('output.xls')
```
使用openpyxl库的示例代码如下:
```python
from openpyxl import Workbook
# 创建一个Workbook对象,即相当于创建了一个Excel文件
workbook = Workbook()
# 创建sheet并命名
sheet1 = workbook.active
sheet1.title = 'Sheet1'
sheet2 = workbook.create_sheet(title='Sheet2')
# 写入数据到sheet1
sheet1['A1'] = 'Hello'
sheet1['B1'] = 'World'
# 写入数据到sheet2
sheet2['A1'] = 'Python'
sheet2['B1'] = 'Excel'
# 保存Excel文件
workbook.save('output.xlsx')
```
以上代码将分别在Excel文件的Sheet1和Sheet2中写入数据,并保存为`output.xls`(使用xlwt库)或`output.xlsx`(使用openpyxl库)。你可以根据实际需求修改代码,添加更多的sheet和数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)