如何在Excel电子表格中删除满足某些条件的行? [英] How to delete rows that satisfy some criteria in an excel spreadsheet?
问题描述
我想创建Excel(xlsx)电子表格的精简版"(即,根据某些条件删除一些行),并且我想知道是否可以使用openpyxl
完成. /p>
在(Python式)伪代码中,我想做的事情看起来像:
wb = openpyxl.reader.excel.load_workbook('/path/to/workbook.xlsx')
sh = wb.get_sheet_by_name('someworksheet')
# weed out the rows of sh according to somecriterion
sh.rows[:] = [r for r in sh.rows if somecriterion(r)]
# save the workbook, with the weeded-out sheet
wb.save('/path/to/workbook_reduced.xlsx')
可以用openpyxl
来完成类似的操作吗?如果可以,怎么办?
2018更新:我今天正在搜索如何删除行,发现该功能已添加到openpyxl 2.5.0-b2中.只是尝试,它完美地工作. 这是我找到答案的链接: https: //bitbucket.org/openpyxl/openpyxl/issues/964/delete_rows-does-not-work-on-deleting
这是删除一行的语法:
ws.delete_rows(index, 1)
其中: "ws"是工作表, 索引"是行号,并且 "1"是要删除的行数.
还有删除列的功能,但我没有尝试过.
I would like to create a "reduced" version of an Excel (xlsx) spreadsheet (i.e. by removing some rows according to some criterion), and I'd like to know if this can be done with openpyxl
.
In (pythonish) pseudo-code, what I want to do would look something like:
wb = openpyxl.reader.excel.load_workbook('/path/to/workbook.xlsx')
sh = wb.get_sheet_by_name('someworksheet')
# weed out the rows of sh according to somecriterion
sh.rows[:] = [r for r in sh.rows if somecriterion(r)]
# save the workbook, with the weeded-out sheet
wb.save('/path/to/workbook_reduced.xlsx')
Can something like this be done with openpyxl
, and if so, how?
2018 update: I was searching how to delete a row today and found that the functionality is added in openpyxl 2.5.0-b2. Just tried and it worked perfectly. Here's the link where I found the answer: https://bitbucket.org/openpyxl/openpyxl/issues/964/delete_rows-does-not-work-on-deleting
And here's the syntax to delete one row:
ws.delete_rows(index, 1)
where: 'ws' is the worksheet, 'index' is the row number, and '1' is the number of rows to delete.
There's also the ability to delete columns, but I haven't tried that.
这篇关于如何在Excel电子表格中删除满足某些条件的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!