用pandas框架替换xlsx工作表中的数据

oaxa6hgo  于 12个月前  发布在  其他
关注(0)|答案(5)|浏览(110)

我有一个带有多个选项卡的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标签。我错过了什么吗?谢谢。

sqserrrh

sqserrrh1#

因为你想覆盖,但是没有直接的选项(就像在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()

字符串

0tdrvxhp

0tdrvxhp2#

自pandas版本1.3.0以来,有一个新参数:“if_sheet_exists”-“error”,“new”,“replace”}

pd.ExcelWriter(r'path/to/file.xlsx', engine='openpyxl', mode='a', if_sheet_exists='replace')

字符串

siotufzp

siotufzp3#

你可以尝试暂时保存所有其他的工作表,然后再把它们加回去。我不认为这会保存任何公式或格式。

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()

字符串

0mkxixxg

0mkxixxg4#

好吧,我已经设法做到了。这不是一个干净的解决方案,一点也不快,但我利用了openpyxl文档来使用pandas,可以在这里找到: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')

字符串
有点混乱,我希望有一个比我更好的解决方案,但这对我来说很有效。

sg24os4d

sg24os4d5#

你可以使用xlwings来完成这个任务。xlwings的一个要求是安装Microsoft Excel。下面是一个例子:

import xlwings as xw
import pandas as pd

path = r"test.xlsx"

df = pd._testing.makeDataFrame()

# The with block inserts df to an existing Excel worksheet, 
# in this case to the one with the name "Town_names".
with xw.App(visible=False):
    wb = xw.Book(path)
    ws = wb.sheets["Town_names"]

    ws.clear()
    ws["A1"].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(path)
    wb.close()

字符串

相关问题