python中将df写入到一个sheet,其他sheet内容不变
时间: 2023-11-27 17:49:49 浏览: 95
可以使用 `openpyxl` 库来实现将 DataFrame 写入到指定的 Excel 文件的指定 Sheet 中,同时保留其他 Sheet 的内容。
首先,需要安装 `openpyxl` 库,可以使用 pip 进行安装:
```python
pip install openpyxl
```
接下来,假设要将 DataFrame 写入到 `example.xlsx` 文件的 `Sheet2` 中,可以按照以下步骤实现:
1. 导入需要的库
```python
import pandas as pd
from openpyxl import load_workbook
```
2. 读取 Excel 文件
```python
# 读取 Excel 文件
book = load_workbook('example.xlsx')
```
3. 获取 Sheet 对象
```python
# 获取 Sheet 对象
writer = pd.ExcelWriter('example.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
sheetname = 'Sheet2'
ws = writer.sheets[sheetname]
```
4. 将 DataFrame 写入到指定 Sheet
```python
# 将 DataFrame 写入到指定 Sheet
df.to_excel(writer, sheet_name=sheetname, index=False, header=False, startrow=ws.max_row+1)
```
最后,记得关闭 writer 对象:
```python
writer.save()
writer.close()
```
完整代码如下:
```python
import pandas as pd
from openpyxl import load_workbook
# 读取 Excel 文件
book = load_workbook('example.xlsx')
# 获取 Sheet 对象
writer = pd.ExcelWriter('example.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
sheetname = 'Sheet2'
ws = writer.sheets[sheetname]
# 将 DataFrame 写入到指定 Sheet
df.to_excel(writer, sheet_name=sheetname, index=False, header=False, startrow=ws.max_row+1)
# 保存并关闭 writer 对象
writer.save()
writer.close()
```
阅读全文