openpyxl写入
时间: 2023-09-12 11:04:35 浏览: 109
使用openpyxl库进行Excel文件的写入操作可以按照以下步骤进行:
1. 导入openpyxl库和需要的模块
```python
from openpyxl import Workbook
from openpyxl import load_workbook
```
2. 新建一个工作簿或者加载已有的工作簿
- 新建工作簿
```python
wb = Workbook()
ws = wb.active
```
- 加载已有工作簿
```python
wb = load_workbook(r'D:\python_files\history\daily\blog\excel_demo.xlsx')
ws = wb['Sheet1']
```
3. 写入数据到工作表中
- 单个单元格写入
```python
ws.cell(1, 1).value = 'new_value' # 在A1单元格写入数据
```
- 循环写入一行数据
```python
last_row_data = all_data[-1 # 获取最后一行的数据
for c in range(len(last_row_data)):
ws.cell(13, c+1).value = last_row_data[c # 在第13行写入一行数据
```
4. 保存工作簿
```python
wb.save(r'D:\python_files\history\daily\blog\excel_demo.xlsx') # 保存工作簿
```
以上就是使用openpyxl库进行Excel文件写入的步骤,你可以根据实际需求进行相应的修改和扩展。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [python操作excel自动化办公: 读取写入excel之openpyxl简单使用详细教程+举例说明](https://blog.csdn.net/Nikolas1/article/details/131087925)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文