本篇文章讲解openpyxl在sheet底部追加一行数据、在指定位置插入一行
1、openpyxl追加一行
append()方法,是在sheet中追加一行数据,参数可以使列表、元祖、range对象、字典、生成器,源码如下:
def append(self, iterable):
"""Appends a group of values at the bottom of the current sheet.
* If it's a list: all values are added in order, starting from the first column
* If it's a dict: values are assigned to the columns indicated by the keys (numbers or letters)
:param iterable: list, range or generator, or dict containing values to append
:type iterable: list|tuple|range|generator or dict
# -*- coding: utf-8 -*-
from openpyxl import Workbook
wb = Workbook() # 默认生成一个名为Sheet的sheet
# 创建sheet
for name in ['a','b']:
ws = wb.create_sheet(name)
# 追加一行
for sheet in wb:
sheet.append(['name','name2'])
# 在A列和B列追加(参数为字典)
for sheet in wb:
sheet.append({'A':'dicta','B':'dictb'})
wb.save('test.xlsx')
2、openpyxl插入一行或多行(插入的是空行),官方文档如下:
You can insert rows or columns using the relevant worksheet methods:
openpyxl.worksheet.worksheet.Worksheet.insert_rows()
The default is one row or column. For example to insert a row at 7 (before the existing row 7):
ws.insert_rows(7) # 在第7行前面插入一行
# -*- coding: utf-8 -*-
from openpyxl import Workbook
wb = Workbook() # 默认生成一个名为Sheet的sheet
# 创建sheet
for name in ['a','b']:
ws = wb.create_sheet(name)
# 追加一行
for sheet in wb:
sheet.append(['name'])
# 第一行插入空行
for sheet in wb:
sheet.insert_rows(1)
# 在第2行往下数3行插入空行(2、3、4行)
for sheet in wb:
sheet.insert_rows(2,3)
wb.save('test.xlsx')