-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBatchFilterService.cs
More file actions
2024 lines (1814 loc) · 70.3 KB
/
Copy pathBatchFilterService.cs
File metadata and controls
2024 lines (1814 loc) · 70.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using Excel = Microsoft.Office.Interop.Excel;
namespace eWorkhelper
{
internal enum BatchFilterMatchMode
{
Equals,
NotEquals,
Contains,
NotContains
}
/// <summary>
/// 进度回调。返回 true 表示调用方要求取消当前操作。
/// </summary>
internal delegate bool BatchFilterCancellationCheck();
/// <summary>
/// 状态文本回调,用于向 UI 汇报长任务进度。
/// </summary>
internal delegate void BatchFilterProgressReport(string message);
/// <summary>
/// 一次批量过滤操作所需的 Excel 上下文。
/// </summary>
/// <remarks>
/// 该类型拥有创建过程中产生的全部 RCW,因此实现 <see cref="IDisposable"/>;
/// 使用方(<c>BatchFilterForm</c>)必须在窗口释放时调用 <see cref="Dispose"/>。
/// <see cref="Application"/> 是 VSTO 宿主项(<c>Globals.ThisAddIn.Application</c>),
/// 归运行时所有,绝不能在此释放。
/// </remarks>
internal sealed class BatchFilterContext : IDisposable
{
private readonly List<object> ownedComObjects = new List<object>();
private bool disposed;
internal Excel.Application Application { get; set; }
internal Excel.Workbook Workbook { get; set; }
internal Excel.Worksheet Worksheet { get; set; }
internal Excel.AutoFilter AutoFilter { get; set; }
internal Excel.Range FilterRange { get; set; }
internal Excel.Range DataRange { get; set; }
internal string ColumnDisplayName { get; set; }
internal int FieldIndex { get; set; }
internal int TargetColumn { get; set; }
internal int HeaderRow { get; set; }
internal int DataRowCount { get; set; }
/// <summary>登记一个在上下文生命周期内必须释放的 RCW。同一 RCW 重复登记会被忽略。</summary>
internal void Track(object comObject)
{
if (comObject != null && Marshal.IsComObject(comObject) && !ownedComObjects.Contains(comObject))
{
ownedComObjects.Add(comObject);
}
}
public void Dispose()
{
if (disposed)
{
return;
}
disposed = true;
// 逆序释放,与获取顺序相反。Application、Workbook、Worksheet 均由宿主/用户持有,
// 不在上下文中 FinalRelease;只释放本次筛选取得并由上下文拥有的范围对象。
for (int index = ownedComObjects.Count - 1; index >= 0; index--)
{
ComHelper.Release(ownedComObjects[index]);
}
ownedComObjects.Clear();
ComHelper.ReleaseBorrowed(Worksheet);
ComHelper.ReleaseBorrowed(Workbook);
AutoFilter = null;
FilterRange = null;
DataRange = null;
Worksheet = null;
Workbook = null;
}
}
internal sealed class BatchFilterResult
{
/// <summary>本次检查的数据行总数。</summary>
internal int CheckedCount { get; set; }
/// <summary>应用筛选后工作表中实际可见的数据行数(-1 表示未统计)。</summary>
internal int VisibleCount { get; set; } = -1;
/// <summary>为 true 时表示 <see cref="CheckedCount"/>/<see cref="MatchedRowCount"/> 有意义,可由调用方展示计数。</summary>
internal bool HasCounts { get; set; }
/// <summary>
/// 由本工具本次条件匹配到的数据行数(仅针对目标列)。
/// 与 <see cref="VisibleCount"/> 可能不同,因为其它字段的筛选会与本次筛选取交集。
/// </summary>
internal int MatchedRowCount { get; set; }
/// <summary>匹配集合超出 Excel 值列表容量或无法安全应用时为 true,此时未改动工作表。</summary>
internal bool Applied { get; set; } = true;
/// <summary>未应用筛选时的说明文本。</summary>
internal string Message { get; set; }
}
internal sealed class BatchFilterInitialState
{
internal IList<string> Conditions { get; set; }
internal BatchFilterMatchMode MatchMode { get; set; }
internal string StatusMessage { get; set; }
}
internal sealed class BatchFilterService
{
/// <summary>单个条件长度上限(Excel 条件字符串上限为 8192 字符)。</summary>
private const int MaxConditionLength = 8192;
/// <summary>xlFilterValues 值列表容量上限。超过后 Excel 会直接抛出 COM 错误。</summary>
private const int MaxFilterValueCount = 10000;
/// <summary>
/// 判断单元格显示文本是否可用。列宽不足时 <c>Range.Text</c> 会返回纯 "#" 串。
/// </summary>
private static readonly Regex OverflowTextPattern = new Regex("^#+$", RegexOptions.Compiled);
private AppliedFilterState currentState;
internal bool TryCreateContext(Excel.Application application, out BatchFilterContext context, out string errorMessage)
{
context = null;
errorMessage = null;
bool handedOff = false;
try
{
if (application == null)
{
errorMessage = "无法获取当前 Excel 应用程序。";
return false;
}
Excel.Workbooks workbooks = null;
try
{
workbooks = application.Workbooks;
if (workbooks == null || workbooks.Count == 0)
{
errorMessage = "没有可用的 Excel 工作簿。";
return false;
}
}
finally
{
ComHelper.Release(workbooks);
}
Excel.Worksheet worksheet = null;
Excel.Range activeCell = null;
try
{
worksheet = application.ActiveSheet as Excel.Worksheet;
activeCell = application.ActiveCell as Excel.Range;
if (worksheet == null || activeCell == null)
{
errorMessage = "没有有效的工作表或活动单元格。";
return false;
}
int targetColumn = activeCell.Column;
Excel.ListObject listObject = null;
try
{
listObject = activeCell.ListObject;
if (listObject != null)
{
bool built = TryCreateListObjectContext(application, worksheet, listObject, targetColumn, out context, out errorMessage);
if (built)
{
// 该分支已将范围对象交给调用方;外层 finally 不得把刚建立的上下文释放掉。
handedOff = true;
}
return built;
}
}
finally
{
ComHelper.ReleaseBorrowed(listObject);
}
bool autoFilterMode = worksheet.AutoFilterMode;
if (autoFilterMode)
{
Excel.AutoFilter autoFilter = null;
Excel.Range existingRange = null;
try
{
autoFilter = worksheet.AutoFilter;
existingRange = autoFilter == null ? null : autoFilter.Range;
if (existingRange == null || !ContainsColumn(existingRange, targetColumn))
{
errorMessage = "当前选择的列不在现有筛选区域内,请选择筛选区域中的列后重试。";
return false;
}
string builtError;
if (TryBuildContext(application, worksheet, autoFilter, existingRange, targetColumn, null, out context, out builtError))
{
// 上下文接管 autoFilter/existingRange 的所有权。
handedOff = true;
return true;
}
errorMessage = builtError;
return false;
}
finally
{
if (!handedOff)
{
ComHelper.Release(existingRange);
ComHelper.Release(autoFilter);
}
}
}
Excel.Range newFilterRange = null;
bool cancelled;
if (!TryCreateFilterRangeFromSelectedHeader(application, worksheet, targetColumn, out newFilterRange, out cancelled, out errorMessage))
{
return false;
}
if (cancelled)
{
return false;
}
// E-07:新建 AutoFilter 后若上下文构建失败,必须把工作表恢复原状。
bool guardPreviousScreenUpdating = false;
bool previousScreenUpdating = true;
try
{
try
{
previousScreenUpdating = application.ScreenUpdating;
guardPreviousScreenUpdating = true;
application.ScreenUpdating = false;
}
catch (COMException)
{
guardPreviousScreenUpdating = false;
}
try
{
newFilterRange.AutoFilter();
Excel.AutoFilter newAutoFilter = worksheet.AutoFilter;
string builtError;
if (!TryBuildContext(application, worksheet, newAutoFilter, newFilterRange, targetColumn, null, out context, out builtError))
{
ComHelper.Release(newAutoFilter);
// 建立失败:撤销刚刚新建的 AutoFilter,避免留下工作表变更。
RollbackSyntheticAutoFilter(newFilterRange);
errorMessage = builtError;
return false;
}
// 上下文接管 newAutoFilter/newFilterRange 的所有权。
handedOff = true;
return true;
}
finally
{
if (guardPreviousScreenUpdating)
{
try
{
application.ScreenUpdating = previousScreenUpdating;
}
catch (Exception)
{
}
}
}
}
finally
{
// 成功交接后 newFilterRange 归上下文所有,由 Dispose 释放。
if (!handedOff)
{
ComHelper.Release(newFilterRange);
}
}
}
finally
{
// 成功交接后,worksheet/activeCell 的所有权归上下文,由 Dispose 统一释放。
ComHelper.ReleaseBorrowed(activeCell);
if (!handedOff)
{
ComHelper.ReleaseBorrowed(worksheet);
}
}
}
catch (COMException)
{
errorMessage = "无法识别或建立 Excel 筛选区域,请确认工作表未受保护并重试。";
return false;
}
catch (Exception ex)
{
errorMessage = "无法启动批量过滤:" + ex.Message;
return false;
}
finally
{
if (!handedOff && context != null)
{
// 未交接给调用方(异常路径):释放本次构建的上下文,避免泄漏。
context.Dispose();
context = null;
}
}
}
internal IList<string> NormalizeConditions(string input)
{
List<string> conditions = new List<string>();
// E-13:去重语义必须与匹配语义一致(大小写不敏感),否则 "abc" 与 "ABC" 会被重复保留。
HashSet<string> unique = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
string[] lines = (input ?? string.Empty).Split(new[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
foreach (string line in lines)
{
string condition = line.Trim();
if (condition.Length > 0 && unique.Add(condition))
{
conditions.Add(condition);
}
}
return conditions;
}
/// <summary>
/// E-12:校验用户输入的条件长度,避免把超长文本直接交给 Excel 触发原始 COM 错误。
/// </summary>
internal static string ValidateConditions(IList<string> conditions)
{
if (conditions == null)
{
return null;
}
foreach (string condition in conditions)
{
if (condition != null && condition.Length > MaxConditionLength)
{
return string.Format(
CultureInfo.CurrentCulture,
"单个过滤条件最多支持 {0} 个字符,第 {1} 个条件长度为 {2}。请拆分或缩短条件后重试。",
MaxConditionLength,
IndexOfCondition(conditions, condition) + 1,
condition.Length);
}
}
return null;
}
private static int IndexOfCondition(IList<string> conditions, string condition)
{
for (int index = 0; index < conditions.Count; index++)
{
if (ReferenceEquals(conditions[index], condition)
|| string.Equals(conditions[index], condition, StringComparison.Ordinal))
{
return index;
}
}
return 0;
}
internal BatchFilterInitialState LoadInitialState(BatchFilterContext context)
{
Excel.Filter filter = GetTargetFilter(context);
if (filter == null || !filter.On)
{
return new BatchFilterInitialState
{
Conditions = new List<string>(),
MatchMode = BatchFilterMatchMode.Contains,
StatusMessage = "请输入过滤条件。"
};
}
string filterSignature = TryGetFilterSignature(filter);
AppliedFilterState state = currentState;
if (state != null && state.Matches(context, filterSignature))
{ return new BatchFilterInitialState
{
Conditions = state.GetConditions(),
MatchMode = state.MatchMode,
StatusMessage = "已恢复上次批量过滤条件。"
};
}
// E-06:与 Apply 统一使用“显示文本”可见性语义。
IList<string> visibleValues = ReadVisibleUniqueValues(context.DataRange);
return new BatchFilterInitialState
{
Conditions = visibleValues,
MatchMode = BatchFilterMatchMode.Equals,
StatusMessage = visibleValues.Count == 0
? "当前筛选无可见数据。"
: string.Format(CultureInfo.CurrentCulture, "已加载当前筛选的 {0} 个可见唯一值。", visibleValues.Count)
};
}
internal BatchFilterResult Apply(
BatchFilterContext context,
IList<string> conditions,
BatchFilterMatchMode mode,
BatchFilterCancellationCheck isCancelled,
BatchFilterProgressReport reportProgress)
{
if (context == null)
{
throw new InvalidOperationException("批量过滤上下文不可用。");
}
string validationError = ValidateConditions(conditions);
if (validationError != null)
{
throw new InvalidOperationException(validationError);
}
Excel.Application application = context.Application;
bool previousScreenUpdating = true;
bool haveScreenUpdating = false;
bool previousEnableEvents = true;
bool haveEnableEvents = false;
Excel.XlCalculation previousCalculation = Excel.XlCalculation.xlCalculationAutomatic;
bool haveCalculation = false;
bool previousCursorSet = false;
Excel.XlMousePointer previousCursor = Excel.XlMousePointer.xlDefault;
try
{
try
{
previousScreenUpdating = application.ScreenUpdating;
haveScreenUpdating = true;
application.ScreenUpdating = false;
}
catch (COMException)
{
}
try
{
previousEnableEvents = application.EnableEvents;
haveEnableEvents = true;
application.EnableEvents = false;
}
catch (COMException)
{
}
// E-05:长任务期间冻结重算,避免每个筛选步骤都触发整表重算。
try
{
previousCalculation = application.Calculation;
haveCalculation = true;
application.Calculation = Excel.XlCalculation.xlCalculationManual;
}
catch (COMException)
{
}
// E-05:等待光标与状态栏进度,均在 finally 中恢复。
try
{
previousCursor = application.Cursor;
previousCursorSet = true;
application.Cursor = Excel.XlMousePointer.xlWait;
}
catch (COMException)
{
previousCursorSet = false;
}
return ApplyCore(context, conditions, mode, isCancelled, reportProgress);
}
finally
{
// E-08:每个恢复动作单独 try/catch,避免恢复失败替换掉在途异常。
if (previousCursorSet)
{
try
{
application.Cursor = previousCursor;
}
catch (Exception)
{
}
}
try
{
application.StatusBar = false;
}
catch (Exception)
{
}
if (haveCalculation)
{
try
{
application.Calculation = previousCalculation;
}
catch (Exception)
{
}
}
if (haveEnableEvents)
{
try
{
application.EnableEvents = previousEnableEvents;
}
catch (Exception)
{
}
}
if (haveScreenUpdating)
{
try
{
application.ScreenUpdating = previousScreenUpdating;
}
catch (Exception)
{
}
}
}
}
private BatchFilterResult ApplyCore(
BatchFilterContext context,
IList<string> conditions,
BatchFilterMatchMode mode,
BatchFilterCancellationCheck isCancelled,
BatchFilterProgressReport reportProgress)
{
IList<CellDisplay> cells = ReadCellDisplays(context, isCancelled, reportProgress);
List<string> matchedValues = new List<string>();
HashSet<string> matchedUnique = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
int matchedCount = 0;
foreach (CellDisplay cell in cells)
{
if (IsMatch(cell, conditions, mode))
{
matchedCount++;
if (matchedUnique.Add(cell.Text))
{
matchedValues.Add(cell.Text);
}
}
}
BatchFilterResult result = new BatchFilterResult
{
CheckedCount = cells.Count,
MatchedRowCount = matchedCount,
HasCounts = true
};
if (matchedCount == cells.Count)
{
// 全部命中:清除该字段的筛选,保持所有行可见。
ClearTargetFieldFilter(context);
}
else if (matchedCount == 0)
{
// 无命中:不应用筛选(隐藏全部行会让用户无法回到数据),明确告知而不是留下 0 行可见。
result.Applied = false;
result.Message = "没有单元格与当前条件匹配,未修改工作表筛选状态。";
}
else
{
if (matchedValues.Count > MaxFilterValueCount)
{
// E-12:不要把一个必然失败的超大值列表交给 Excel。
result.Applied = false;
result.Message = string.Format(
CultureInfo.CurrentCulture,
"匹配到 {0} 个唯一值,超过 Excel 筛选值列表上限({1} 项),未修改工作表。请增加条件以缩小范围。",
matchedValues.Count,
MaxFilterValueCount);
}
else
{
object[] criteria = BuildFilterCriteria(matchedValues);
ApplyNativeFilter(context, criteria);
}
}
if (result.Applied)
{
// E-06:报告实际可见行数,而不是内存中的条件匹配数
//(其它字段的筛选会与本次筛选取交集,两者可能不同)。
result.VisibleCount = CountVisibleDataRows(context);
}
Excel.Filter filter = GetTargetFilter(context);
bool filterOn = filter != null && filter.On;
currentState = new AppliedFilterState(
context,
conditions,
mode,
filterOn ? TryGetFilterSignature(filter) : null);
return result;
}
/// <summary>
/// 统计目标数据列中应用筛选后实际可见的行数(返回总数后再减去被其它字段筛掉的行)。
/// </summary>
private static int CountVisibleDataRows(BatchFilterContext context)
{
Excel.Range dataRange = context.DataRange;
if (dataRange == null)
{
return -1;
}
int visibleRows;
Excel.Range visibleRange = null;
try
{
try
{
visibleRange = dataRange.SpecialCells(Excel.XlCellType.xlCellTypeVisible);
}
catch (COMException)
{
// 没有可见单元格时 SpecialCells 会抛 COM 异常。
return 0;
}
if (visibleRange == null)
{
return 0;
}
int areaCount = CountAreas(visibleRange);
visibleRows = 0;
for (int areaIndex = 1; areaIndex <= areaCount; areaIndex++)
{
Excel.Range area = null;
Excel.Range areaRows = null;
try
{
area = GetArea(visibleRange, areaIndex);
if (area == null)
{
continue;
}
areaRows = area.Rows;
visibleRows += areaRows.Count;
}
finally
{
ComHelper.Release(areaRows);
ComHelper.Release(area);
}
}
}
finally
{
ComHelper.Release(visibleRange);
}
return visibleRows;
}
internal bool Clear(BatchFilterContext context)
{
if (context == null)
{
return false;
}
AppliedFilterState state = currentState;
if (state == null || !state.Matches(context))
{
return false;
}
Excel.Application application = context.Application;
bool previousScreenUpdating = true;
bool haveScreenUpdating = false;
bool previousEnableEvents = true;
bool haveEnableEvents = false;
bool previousCursorSet = false;
Excel.XlMousePointer previousCursor = Excel.XlMousePointer.xlDefault;
try
{
try
{
previousScreenUpdating = application.ScreenUpdating;
haveScreenUpdating = true;
application.ScreenUpdating = false;
}
catch (COMException)
{
}
try
{
previousEnableEvents = application.EnableEvents;
haveEnableEvents = true;
application.EnableEvents = false;
}
catch (COMException)
{
}
try
{
previousCursor = application.Cursor;
previousCursorSet = true;
application.Cursor = Excel.XlMousePointer.xlWait;
}
catch (COMException)
{
previousCursorSet = false;
}
ClearTargetFieldFilter(context);
currentState = null;
return true;
}
finally
{
if (previousCursorSet)
{
try
{
application.Cursor = previousCursor;
}
catch (Exception)
{
}
}
try
{
application.StatusBar = false;
}
catch (Exception)
{
}
if (haveEnableEvents)
{
try
{
application.EnableEvents = previousEnableEvents;
}
catch (Exception)
{
}
}
if (haveScreenUpdating)
{
try
{
application.ScreenUpdating = previousScreenUpdating;
}
catch (Exception)
{
}
}
}
}
private static bool TryCreateListObjectContext(
Excel.Application application,
Excel.Worksheet worksheet,
Excel.ListObject listObject,
int targetColumn,
out BatchFilterContext context,
out string errorMessage)
{
context = null;
errorMessage = null;
Excel.Range listObjectRange = null;
Excel.Range dataBodyRange = null;
bool previousShowAutoFilter = false;
bool haveShowAutoFilter = false;
bool changedShowAutoFilter = false;
try
{
// E-07:先记录 ShowAutoFilter 原值,失败时回滚。
try
{
previousShowAutoFilter = listObject.ShowAutoFilter;
haveShowAutoFilter = true;
}
catch (COMException)
{
haveShowAutoFilter = false;
}
listObjectRange = listObject.Range;
dataBodyRange = listObject.DataBodyRange;
if (dataBodyRange == null)
{
errorMessage = "当前表格没有可过滤的数据行。";
return false;
}
if (haveShowAutoFilter && !previousShowAutoFilter)
{
listObject.ShowAutoFilter = true;
changedShowAutoFilter = true;
}
int fieldIndex = targetColumn - listObjectRange.Column + 1;
Excel.ListColumn listColumn = null;
Excel.Range targetDataRange = null;
Excel.AutoFilter listAutoFilter = null;
try
{
listColumn = listObject.ListColumns[fieldIndex];
targetDataRange = listColumn.DataBodyRange;
listAutoFilter = listObject.AutoFilter;
bool built = TryBuildContext(
application,
worksheet,
listAutoFilter,
listObjectRange,
targetColumn,
targetDataRange,
out context,
out errorMessage);
if (!built && changedShowAutoFilter)
{
// 建立失败:恢复原来的 ShowAutoFilter 状态。
try
{
listObject.ShowAutoFilter = previousShowAutoFilter;
}
catch (Exception)
{
}
}
return built;
}
finally
{
// 这些中间 RCW 一旦交给上下文就由上下文负责释放;未交接的在这里释放。
if (context == null)
{
ComHelper.Release(listAutoFilter);
ComHelper.Release(targetDataRange);
}
ComHelper.Release(listColumn);
}
}
catch (COMException)
{
errorMessage = "无法识别表格筛选区域,请确认工作表未受保护并重试。";
return false;
}
finally
{
// 成功交接后,listObjectRange/dataBodyRange 的所有权归上下文,由 Dispose 统一释放。
if (context == null)
{
ComHelper.Release(dataBodyRange);
ComHelper.Release(listObjectRange);
}
}
}
private static bool TryCreateFilterRangeFromSelectedHeader(
Excel.Application application,
Excel.Worksheet worksheet,
int targetColumn,
out Excel.Range filterRange,
out bool cancelled,
out string errorMessage)
{
filterRange = null;
cancelled = false;
errorMessage = null;
object selection = null;
Excel.Range selectedRange = null;
Excel.Range firstCell = null;
Excel.Range region = null;
Excel.Range headerCell = null;
try
{
selection = application.InputBox("当前区域尚未启用 Excel 筛选,请选择数据的标题行。", "批量过滤", Type: 8);
selectedRange = selection as Excel.Range;
if (selectedRange == null)
{
cancelled = selection is bool && !(bool)selection;
if (!cancelled)
{
errorMessage = "请选择有效的标题行单元格。";
}
return false;
}
// E-14:工作表校验必须同时比较工作簿与工作表,避免同名工作表误判。
Excel.Worksheet selectedWorksheet = null;
try
{
selectedWorksheet = selectedRange.Worksheet as Excel.Worksheet;
}
catch (COMException)
{
selectedWorksheet = null;
}
bool sameWorksheet;
try
{
sameWorksheet = IsSameWorksheet(selectedWorksheet, worksheet);
}
finally
{
ComHelper.Release(selectedWorksheet);
}
if (!sameWorksheet)
{
errorMessage = "请选择当前工作表中的标题行。";
return false;
}
int firstSelectedRow = selectedRange.Row;
int selectedRowCount;
Excel.Range selectedRows = null;
try
{
selectedRows = selectedRange.Rows;
selectedRowCount = selectedRows.Count;
}
finally
{
ComHelper.Release(selectedRows);
}
int lastSelectedRow = firstSelectedRow + selectedRowCount - 1;
if (firstSelectedRow != lastSelectedRow)
{
errorMessage = "请选择单一标题行。";
return false;
}
firstCell = selectedRange.Cells[1, 1] as Excel.Range;
if (firstCell == null)
{
errorMessage = "请选择有效的标题行单元格。";
return false;
}
region = firstCell.CurrentRegion;
if (region == null)
{
errorMessage = "无法识别所选标题行所在的数据区域。";