openpyxl表格多级自定义排序
时间: 2023-07-18 08:18:54 浏览: 136
如果你想对一个 Excel 表格进行多级自定义排序,可以使用 openpyxl 模块中的 `Sorter()` 类。具体步骤如下:
1. 导入 openpyxl 模块并打开 Excel 文件:
```python
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
ws = wb.active
```
2. 创建一个 `Sorter()` 对象,并配置排序规则。例如,如果你想按照第一列和第二列升序排序,可以这样配置:
```python
sorter = openpyxl.worksheet.sorting.Sorter()
sorter.add_sort_condition(1, ascending=True)
sorter.add_sort_condition(2, ascending=True)
```
其中,`add_sort_condition()` 方法的第一个参数为要排序的列的索引(从 1 开始),第二个参数为排序方式(`True` 表示升序,`False` 表示降序)。
3. 调用 `sort()` 方法对表格进行排序:
```python
ws.sort(sorter)
```
4. 保存 Excel 文件:
```python
wb.save('example_sorted.xlsx')
```
完整代码示例:
```python
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
ws = wb.active
sorter = openpyxl.worksheet.sorting.Sorter()
sorter.add_sort_condition(1, ascending=True)
sorter.add_sort_condition(2, ascending=True)
ws.sort(sorter)
wb.save('example_sorted.xlsx')
```
阅读全文
相关推荐

















