如何使用Python在Excel中的特定行之后附加一行

我是Python的新手。 现在只是玩openpyxl 。 我想用Python编写一个电子表格,但是单元格的格式和样式很复杂,而且不一定每次都是正确的。

所以我想制作一个模板excel文件,并始终从文件中读取并保存为新文件。 要做到这一点,我已经避免覆盖一些行。 目前我使用的代码来追加Excel行,因为我不会附加大小。

有没有办法像第7行那样从某一行追加行?

我的代码是:

 def Output(message): wb = Workbook() ws = wb.active ws.title = 'Quotation' Row_size = len(message) for i in range (Row_size): message_line = message[i] ws.append(message_line) wb.save('Quatation.xlsx') 

而不是使用ws.append() ,使用ws.cell()函数来指定所需的行和列。 enumerate()可以用来给你从7开始的传入列表中的每个条目的行号。

 from openpyxl import Workbook def Output(message): wb = Workbook() ws = wb.active ws.title = 'Quotation' for row, text in enumerate(message, start=7): ws.cell(column=1, row=row, value=text) wb.save('Quotation.xlsx') Output(['hello', 'world']) 

给你:

excel截图


请注意,如果您每行传递多个单元格,则需要第二个循环,如下所示:

 from openpyxl import Workbook def Output(message): wb = Workbook() ws = wb.active ws.title = 'Quotation' Row_size = len(message) for row, row_entries in enumerate(message, start=7): for column, value in enumerate(row_entries, start=1): ws.cell(column=column, row=row, value=value) wb.save('Quotation.xlsx') Output([['hello', 'world'], ['this', 'is', 'another', 'line']]) 

从pandas模块使用DataFrame.to_excel。