【问题标题】:Deleting Entire blank row in an existing Excel Sheet using Python使用Python删除现有Excel工作表中的整个空白行
【发布时间】:2016-01-04 06:12:33
【问题描述】:

如何使用 Python 从现有 Excel 工作表中删除整个空白行?

我需要一个不需要的解决方案: 包括读取整个文件并在不删除行的情况下重写它。

有没有直接的解决方案?

【问题讨论】:

  • 哇,全部大写?你试过什么?是只有一个空白行还是有多个空白行?
  • 我要准确执行excel的“删除行”操作,删除行,其他行上移
  • 如果我可以从 Excel 表中删除一行就可以了。

标签: python-2.7 xlrd xlwt xlutils


【解决方案1】:

我使用 Pandas 包实现了....

import pandas as pd

#Read from Excel
xl= pd.ExcelFile("test.xls")

#Parsing Excel Sheet to DataFrame
dfs = xl.parse(xl.sheet_names[0])

#Update DataFrame as per requirement
#(Here Removing the row from DataFrame having blank value in "Name" column)

dfs = dfs[dfs['Name'] != '']

#Updating the excel sheet with the updated DataFrame

dfs.to_excel("test.xls",sheet_name='Sheet1',index=False)

【讨论】:

  • 看起来这个解决方案只适用于 1 列,但如果有多个列怎么办?此外,这一行 dfs = dfs[dfs['Name'] != ''] 给出了类型错误 TypeError: invalid type comparison
  • 是的,你是对的。此语句不能应用于多列。如果我们想删除 Name 为“abc”且 Salary 为 2000 的行,我们无法使用此语句执行此操作。但是,如果我们想删除 Name 为“abc”或 Salary 为 2000 的行,我们可以通过一遍又一遍地编写此语句来做到这一点,然后最终将 DataFrame 转换为 Excel。
【解决方案2】:

如果使用内存不是问题,您可以使用额外的数据帧来实现。

import pandas as pd

#Read from Excel
xl= pd.ExcelFile("test.xls")

dfs = xl.parse(xl.sheet_names[0])
df1 = dfs[dfs['Sal'] == 1000]
df1 = df1[df1['Message']=="abc"]

ph_no = df1['Number']

print df1

【讨论】:

    【解决方案3】:

    要删除 Excel 行,比如第 5 行,第 1 列无关紧要:

    sh.Cells(5,1).EntireRow.Delete()
    

    要删除一系列 Excel 行,例如第 5 到 20 行

    sh.Range(sh.Cells(5,1),sh.Cells(20,1)).EntireRow.Delete()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      相关资源
      最近更新 更多