在简单Excel文件中删除特征行
我需要在一个简单的Excel文件中删除一些行。
比如说,我想删除那些B列不为空的行。
我想到的办法其实不是直接“删除”,而是重命名一个新创建的文件:
import os
import xlwt
from xlrd import open_workbook
old_file = open_workbook('C:\\file.xls',formatting_info=True)
old_sheet = old_file.sheet_by_index(0)
new_file = xlwt.Workbook(encoding='utf-8', style_compression = 0)
new_sheet = new_file.add_sheet('Sheet1', cell_overwrite_ok = True)
contents = []
for row in range(old_sheet.nrows):
a = old_sheet.cell(row,0).value
b = old_sheet.cell(row,1).value
if len(b) < 1:
contents.append(a)
for c, content in enumerate(contents):
new_sheet.write(c, 0, content)
new_file.save('C:\\file_1.xls')
os.remove('C:\\file.xls')
os.rename('C:\\file_1.xls', 'C:\\file.xls')
嗯,这其实并不是在真正删除行,不过这也算是一种可行的方法。
还有没有更好的方法来做到这一点,比如考虑更多的条件呢?
3 个回答
2
试试 pyexcel
:
>>> import pyexcel
>>> r=pyexcel.FilterableReader("mysample.xls")
>>> keep_row_func = lambda row: row[1] == ''
>>> r.filter(pyexcel.filters.RowValueFilter(keep_row_func))
>>> pyexcel.utils.to_array(r)
[111.0, '', 222.0, '', 444.0, '', 666.0, '', 777.0, '']
>>> w=pyexcel.Writer("output.xlsx") # or output.ods, output.csv
>>> w.write_reader(r)
>>> w.close()
使用 pyexcel
,你可以在这些文件格式上运行上面的脚本:ods、csv、xls、xlsx 和 xlsm。相关文档可以在这里找到:http://pythonhosted.org//pyexcel/
2
用csv文件比用xls文件更容易处理。