【问题标题】:Insert a title at the beginning of the Excel worksheet在 Excel 工作表的开头插入标题
【发布时间】:2018-03-27 12:35:12
【问题描述】:
row = 5  
column = 0
writer = pd.ExcelWriter(file_name, engine='openpyxl')    
response = send_request('2017-2018-regular', item).content
df = pd.read_csv(io.StringIO(response.decode('utf-8')))
df.to_excel(writer, sheets, startrow=row, startcol=column, index=False)

考虑到我正在使用pandas 和openpyxl,我想在我的Excel 表格顶部放一个简单的标题。我怎么能做这种事?我希望该标题可以显示在工作表的顶部(startrow=0,startcol=0)。请举例说明如何使用它。

我知道问题Write dataframe to excel with a title 是相关的,但我不能使用它,原因很简单,引擎不同。我使用openpyxl lib,他们在答案中使用了xlsxwriter lib。 write_string 的等价物是什么,但pandas 是什么?

【问题讨论】:

  • 您的问题是什么,如何插入标题,或者openpyxl 中的write_string 的等价物是什么?另外,我不确定,但 Excel 0 中的 openpyxl 或 pandas 列/行是基于吗?在 Excel 中没有第 0 列。您需要从 1 开始。也许这就是这里的问题?

标签: python excel pandas openpyxl


【解决方案1】:

在 openpyxl 中,第一行/列以 1 而不是 0 开头,因此 row=1,column=1 将是您需要开始写入的第一个 (0,0) 左上角单元格

检查以下示例。

from openpyxl import Workbook

wb = Workbook()
dest_filename = 'empty_book.xlsx'

ws1 = wb.active #first default sheet if you want to create new one use wb.create_sheet(title="xyz")
ws1.title = "Title set example"

for col in range(1, 10):
    ws1.cell(column=col, row=1, value="Title_{0}".format(col))
wb.save(filename = dest_filename)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    相关资源
    最近更新 更多