我有一个带有多个标签的xlsx文件,其中一个是Town_names
,其中已经有一些数据。
我想用一个数据帧-Town_namesDF
-覆盖这些数据,同时保持其余的xlsx选项卡不变。
我尝试了以下操作:
with pd.ExcelWriter(r'path/to/file.xlsx', engine='openpyxl', mode='a') as writer:
Town_namesDF.to_excel(writer,sheet_name='Town_names')
writer.save()
writer.close()
但是最终会创建一个新标签Town_names1
而不是覆盖Town_names
标签。我想念什么吗?谢谢。
答案 0 :(得分:1)
您可以尝试使用此方法暂时存储所有其他工作表,然后将其重新添加。我认为这不会保存任何公式或格式。
Store_sheet1=pd.read_excel('path/to/file.xlsx',sheetname='Sheet1')
Store_sheet2=pd.read_excel('path/to/file.xlsx',sheetname='Sheet2')
Store_sheet3=pd.read_excel('path/to/file.xlsx',sheetname='Sheet3')
with pd.ExcelWriter(r'path/to/file.xlsx', engine='openpyxl', mode='a') as writer:
Town_namesDF.to_excel(writer,sheet_name='Town_names')
Store_sheet1.to_excel(writer,sheet_name='Sheet1')
Store_sheet2.to_excel(writer,sheet_name='Sheet2')
Store_sheet3.to_excel(writer,sheet_name='Sheet3')
writer.save()
writer.close()
答案 1 :(得分:1)
由于您要覆盖,但是没有直接选择(例如在julia的XLSX中,有cell_ref的选择)。只需删除重复项(如果存在),然后写。
with pd.ExcelWriter('/path/to/file.xlsx',engine = "openpyxl", mode='a') as writer:
workBook = writer.book
try:
workBook.remove(workBook['Town_names'])
except:
print("worksheet doesn't exist")
finally:
df.to_excel(writer, sheet_name='Town_names')
writer.save()
答案 2 :(得分:0)
好吧,我已经做到了。这不是一个干净的解决方案,根本不是很快,但是我利用openpyxl文档来处理在这里找到的熊猫:https://openpyxl.readthedocs.io/en/latest/pandas.html
我正在有效地选择Town_names
工作表,用ws.delete_rows()
清除它,然后将数据框的每一行附加到工作表中。
wb = openpyxl.load_workbook(r'path/to/file.xlsx')
ws = wb.get_sheet_by_name('Town_names')
ws.delete_rows(0, 1000)
wb.save(r'path/to/file.xlsx')
wb = openpyxl.load_workbook(r'path/to/file.xlsx')
activeSheet = wb.get_sheet_by_name('Town_names')
for r in dataframe_to_rows(Town_namesDF, index=False, header=True):
activeSheet.append(r)
for cell in activeSheet['A'] + activeSheet[1]:
cell.style = 'Pandas'
wb.save(r'path/to/file.xlsx')
有点混乱,我希望有比我更好的解决方案,但这对我有用。
答案 3 :(得分:0)
嗨,您可以将xlwings用于该任务。这是一个例子。
import xlwings as xw
import pandas as pd
filename = "test.xlsx"
df = pd.read_excel(filename, "Town_names")
# Do your modifications of the worksheet here. For example, the following line "df * 2".
df = df * 2
app = xw.App(visible=False)
wb = xw.Book(filename)
ws = wb.sheets["Town_names"]
ws.clear()
ws["A1"].options(pd.DataFrame, header=1, index=False, expand='table').value = df
# If formatting of column names and index is needed as xlsxwriter does it, the following lines will do it.
ws["A1"].expand("right").api.Font.Bold = True
ws["A1"].expand("down").api.Font.Bold = True
ws["A1"].expand("right").api.Borders.Weight = 2
ws["A1"].expand("down").api.Borders.Weight = 2
wb.save(filename)
app.quit()