Skip to main content
 首页 » 编程设计

python之尝试使用 Python 从 excel 电子表格中删除第一行

2025年04月02日14bhlsheji

这是我的第一个问题,所以如果我不遵守完美的礼仪,请原谅我。我一直在寻找答案大约 6 个小时,所以我想是时候问了。我是 Python 的新手,我正在尝试使用 Selenium 自动输入数据。我做得很好,但卡在了从 Excel 中提取数据的部分。数据提取不是问题,但告诉我的 excel 删除第一行或移动到下一行是问题。这是我的脚本示例:

    import pandas as pd 
from pandas import ExcelWriter 
import numpy as np 
 
xl = pd.ExcelFile('C:\\Users\\Steph_000\\Desktop\\students2.xlsx') 
xl 
 
wr = pd.ExcelWriter('C:\\Users\\Steph_000\\Desktop\\students2.xlsx') 
 
xl.sheet_names 
 
['Sheet1'] 
 
df = xl.parse('Sheet1') #This reads the sheet into a dataframe 
df 
 
cp = pd.read_excel('C:\\Users\\Steph_000\\Desktop\\students2.xlsx') 
 
IDNum = cp[:1] #This pulls the first row as a variable 
 
print(IDNum) #This is where it prints to the search bar to look the student up 
 
chart = cp[1:] #This pulls everything but the first row as a variable 
 
print(chart) 
 
df.to_excel(wr, 'Sheet1') 
wr.save() #This is supposed to overwrite it, but just saves it as blank 

无论我做什么,我都无法让它向上移动行或类似的东西。我真的很挣扎也很沮丧。如果必须的话,我会使用与 Pandas 不同的 Python 包装器,但我已经尝试过 openpyxl、xlrd 和 xlwr,但都无济于事!拉我的头发,在此先感谢!

请您参考如下方法:

看下面的例子:

  • 缺少引擎='xlsxwriter'
  • 缺少 sheet_name='Sheet1

看看这个:

            import pandas as pd 
            #Create a Pandas dataframe from the data. 
            df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]}) 
 
            # Create a Pandas Excel writer using XlsxWriter as the engine. 
            writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter') 
 
            # Convert the dataframe to an XlsxWriter Excel object. 
            df.to_excel(writer, sheet_name='Sheet1') 
 
            # Close the Pandas Excel writer and output the Excel file. 
            writer.save() 

http://xlsxwriter.readthedocs.io/working_with_pandas.html