显示现有内容工作表

时间:2017-10-19 17:10:44

标签: python excel

def test(sheet, row=2):

    writer = pd.ExcelWriter("testing.xlsx", engine='openpyxl')

    df1 = pd.DataFrame(['Title'], index=[0])
    df2 = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'], 
                       'income': [40000, 50000, 42000]})

    df1.to_excel(writer, sheet, startrow=0, startcol=0, header=None, \
                 index=False)
    df2.to_excel(writer, sheet, startrow=row, index=False)

    writer.save()
    writer.close()

test('aaa')

目前,这个小功能创建了一个Excel工作表。

说明:

假设Excel工作表存在。我想用下面的代码写下现有行的其他内容。

In [1]: import pandas as pd

In [2]: writer = pd.ExcelWriter("testing.xlsx", engine='openpyxl')

In [4]: from openpyxl import load_workbook

In [5]: book = load_workbook("testing.xlsx")

In [6]:     df3 = pd.DataFrame({'amount': ['Chest', 'Bras', 'Braa'], 
   ...:                        'income': [40000, 50000, 42000]})
   ...: 

In [8]: writer.book = book

In [9]: ws = book.get_sheet_by_name('aaa')

In [10]: writer.book
Out[10]: <openpyxl.workbook.workbook.Workbook at 0x7f9add4e3048>

In [12]: writer.book.sheetnames
Out[12]: ['aaa']

In [13]: row = ws.max_row

In [14]: row
Out[14]: 6

In [15]: df3.to_excel(writer, "aaa", startrow=row + 2, index=False)

In [16]: writer.save()

这段代码几乎是我想要的。它会创建一个新的工作表aaa1,并将df的内容放在第8行,就像通常那样。我希望aaa1的内容低于aaa1的内容,而不是创建新工作表aaa。我怎么能解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

不幸的是,如果您只是使用pandas.DataFrame.to_excel,那将无法实现。如果您打算在第二部分使用openpyxl,我会在下面找到解决方案。我使用Pandas样式来格式化单元格的方式与第一部分格式化的方式相同。

import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows

writer = pd.ExcelWriter("testing.xlsx", engine='openpyxl')

book = load_workbook("testing.xlsx")

df3 = pd.DataFrame({'amount': ['Chest', 'Bras', 'Braa'], 
                'income': [40000, 50000, 42000]})

writer.book = book
ws = book['aaa']

row = ws.max_row

#best way to replicate your insertion of 2 blank rows which 
ws.append(tuple())
ws.append(tuple())

for r in dataframe_to_rows(df3, index=False, header=True):
    ws.append(r)

#a quick way to give you the same style as you get with the first part
for row in ws.iter_rows(min_row=row +3, max_col=2, max_row=row +3):
    for cell in row:
        cell.style = 'Pandas'

writer.save()

使用所需的输出: Excel Output