新列保持格式化 xlwings

New column keep formatting xlwings

我想在 read/write tables to/from excel-文件通过 xlwings。这是一个示例,我首先连接到一个空的 excel-文件 Book1.xlsx;

import xlwings as xw
book = xw.Book('Book1.xlsx')
sheet = book.sheets['Sheet1']

插入一个 table 的小 datetime

import pandas as pd
from datetime import datetime
df = pd.DataFrame(columns=[datetime(2020,10,31)], index=['a', 'b', 'c'])
df.index.name = 'My table'
df.loc[:, datetime(2020,10,31)] = [100,200,300]
sheet.range('A1').value = df

现在我手动格式化 excel 文件中的 table,这是生成的图片

现在有一个新的月份,我们应该添加新的值。所以我从 excel 文件中读取了 table 并添加了一个像这样的新列

df = sheet.range('A1').options(pd.DataFrame, expand='table').value
new_month = datetime(2020,11,30)
df.loc[:, new_month] = [101,202,301]

当我将数据帧写回 excel 文件时,新列没有格式。

sheet.range('A1').value = df

见下图。任何 xlwings-解决这个问题的方法?

您可以将格式复制并粘贴到新列中。看例子:

import xlwings as xw

book = xw.Book(r"Book1.xlsx")
sheet = book.sheets["Sheet1"]

sheet.range("B1").expand("down").copy()
sheet.range("B1").expand("table").paste(paste="formats")
sheet.api.Application.CutCopyMode = False