python生成结果保存到excel
时间: 2023-12-12 07:05:38 浏览: 71
要将Python生成的结果保存到Excel中,您需要使用第三方库,如pandas或openpyxl。
使用pandas:
1. 安装pandas库:
```python
pip install pandas
```
2. 导入pandas库:
```python
import pandas as pd
```
3. 创建一个DataFrame并将数据填充到其中:
```python
data = {'Name': ['John', 'Mike', 'Sarah', 'Emily'],
'Age': [25, 30, 28, 32],
'Gender': ['Male', 'Male', 'Female', 'Female']}
df = pd.DataFrame(data)
```
4. 将DataFrame写入Excel文件:
```python
writer = pd.ExcelWriter('output.xlsx')
df.to_excel(writer, index=False)
writer.save()
```
使用openpyxl:
1. 安装openpyxl库:
```python
pip install openpyxl
```
2. 导入openpyxl库:
```python
from openpyxl import Workbook
```
3. 创建一个Workbook和Worksheet对象并将数据填充到其中:
```python
wb = Workbook()
ws = wb.active
data = [['Name', 'Age', 'Gender'],
['John', 25, 'Male'],
['Mike', 30, 'Male'],
['Sarah', 28, 'Female'],
['Emily', 32, 'Female']]
for row in data:
ws.append(row)
```
4. 将Workbook保存到Excel文件:
```python
wb.save('output.xlsx')
```
阅读全文