我有一个名为MasterFile的Excel文件。在MasterFile中,我有多个带有公式的工作表。我想使用下面的代码来更新MasterFile中的一张工作表,而不会覆盖我的任何数据或公式。
到目前为止,这是我的代码:
from bs4 import BeautifulSoup
import requests
import pandas as pd
from openpyxl import load_workbook
url = 'http://www.baseballpress.com/lineups'
soup = BeautifulSoup(requests.get(url).text, 'html.parser')
players = [i.text for i in soup.find_all('a', {'class': 'player-link'})]
my_dict = (players)
df = pd.DataFrame(pd.Series(my_dict))
writer = pd.ExcelWriter('my2nd_webscrape.xlsx')
df.to_excel(writer,'Sheet1')
writer.save()
我在How to write to an existing excel file without breaking formulas with openpyxl?中找到了有关此主题的一些信息,但是我不确定如何调整代码。
答案 0 :(得分:0)
尝试一下:
from bs4 import BeautifulSoup
import requests
import pandas as pd
from openpyxl import load_workbook
book = load_workbook('my2nd_webscrape.xlsx')
writer = pd.ExcelWriter('my2nd_webscrape.xlsx')
writer.book = book
url = 'http://www.baseballpress.com/lineups'
soup = BeautifulSoup(requests.get(url).text, 'html.parser')
players = [i.text for i in soup.find_all('a', {'class': 'player-link'})]
my_dict = (players)
df = pd.DataFrame(pd.Series(my_dict))
df.to_excel(writer,'Sheet1')
writer.save()
writer.close()