[英]Sort a worksheet by a column using Interop
I've found various related code on the Internet but nothing seems to work.我在互联网上找到了各种相关代码,但似乎没有任何效果。 Maybe someone can point out my error:也许有人可以指出我的错误:
// Get a Range of the data to sort
// (I also tried to use _worksheet.UsedRange, but it fails - why?)
var dataToSort = _worksheet.Range["A2", $"Z{lastLine}"];
// Sort range
dataToSort.Sort(_worksheet.Range["A2"]);
Funny enough it resorts the columns instead of the rows...有趣的是,它使用列而不是行......
Actually I want to write something like this:其实我想写这样的东西:
_worksheet.Sort(columnIndex: 1);
But I can't find a suitable overload.但我找不到合适的重载。
My Sheet looks like this:我的工作表如下所示:
1 | | |
2 | Z | Data2 |
3 | A | Data1 |
I want it to look like this afterwards:我希望它以后看起来像这样:
1 | | |
2 | A | Data1 |
3 | Z | Data2 |
(Using Excel 2019 and Excel Interop 15 for an xlsx file) (将 Excel 2019 和 Excel 互操作 15 用于 xlsx 文件)
Ouch, for whatever reason the sort orientation default is xlSortRows
.哎呀,无论出于何种原因, 排序方向默认为xlSortRows
。 I had to switch to xlSortColumns
and now it works with this simple oneliner:我不得不切换到xlSortColumns
,现在它可以与这个简单的 oneliner 一起使用:
_worksheet.UsedRange.Sort(_worksheet.Columns[1], Orientation: XlSortOrientation.xlSortColumns);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.