我正在尝试获取表格的过滤器,以便在进行一些修改后重新应用它们。一切都很好,但是当过滤器在Date列上时,麻烦就开始了。这就是我这样做的方式:
for (int i = 1; i <= filters.Count; i++)
{
FilterTemp f = new FilterTemp();
f.On = filters[i].On;
if (f.On)
{
f.Field = i;
try
{
f.Criteria1 = filters[i].Criteria1;
}
catch { }
f.Operator = (int)filters[i].Operator;
try
{
f.Criteria2 = filters[i].Criteria2;
}
catch { }
}
fs.Add(f);
}
当过滤器位于文本或数字列上时,一切都运行得很漂亮,但是当按年,月或日过滤日期列时,我在第5行尝试获取“Criteria1”时会出现异常。
我尝试将运算符更改为xlFilterDynamic,如此MSDN帖子的回答所述:https://social.msdn.microsoft.com/Forums/vstudio/en-US/15ec8d69-3e6f-450d-82c0-ca53e63c8f64/getting-data-of-list-object-filters-for-date-column?forum=vsto
这样的事情:
for (int i = 1; i <= filters.Count; i++)
{
FilterCache f = new FilterCache();
f.On = filters[i].On;
if (f.On)
{
f.Field = i;
try
{
f.Criteria1 = filters[i].Criteria1;
}
catch
{
filters[i].Operator = XlAutoFilterOperator.xlFilterDynamic;
f.Criteria1 = filters[i].Criteria1;
}
f.Operator = (int)filters[i].Operator;
if (f.Operator == 0)
f.Operator = (int)XlAutoFilterOperator.xlAnd;
try
{
f.Criteria2 = filters[i].Criteria2;
}
catch { }
}
fs.Add(f);
}
没有成功。过滤器[i] .Criteria1现在永远返回1,与我在该日期列上使用的过滤器无关。
为了模拟此问题,需要在Excel工作表上创建一个表,然后在列中放置一些随机日期。然后,过滤此列,选择至少3个不同的日期。运行代码。
在stackoverflow上已有关于此的帖子:Excel VSTO - accessing AutoFilter's Array Criteria throws exceptions
......但是没有令人满意的答案,或者可能有点难以理解这个问题。
FilterTemp类:
public class FilterTemp
{
public bool On;
public object Field;
public object Criteria1;
public int Operator;
public object Criteria2;
}
答案 0 :(得分:0)
所以这只是一个想法最终目标是将日期返回给客户端,以便可以通过AutoFilter重新应用,如此处
string[] FilterList = new string[] { "10/31/2013", "5/4/2013" };
visibleCells.AutoFilter(1, FilterList.Length > 0 ? FilterList.ToArray() : Type.Missing, Excel.XlAutoFilterOperator.xlFilterValues, Type.Missing, true);
希望这会给你一个提示如何继续。我有一天会尝试敲定它。 所有代码都以GitHub
为例using System;
using System.Collections.Generic;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
namespace AutoFilterRetriever
{
/// <summary>
/// An example class how to get AutoFilter criteria from internal XML representation
/// </summary>
public class CriteriaFilterRetriever : IDisposable
{
private readonly Excel.Worksheet wks;
private readonly string filePath;
private Stream docStream;
private SpreadsheetDocument openXmlDoc;
private WorkbookPart wkb;
public CriteriaFilterRetriever(Excel.Worksheet sheet)
{
wks = sheet;
filePath = sheet.Application.ActiveWorkbook.FullName;
if (!filePath.Contains("\\"))
{
throw new FileLoadException("Save the file in order to get autofilter criteria");
}
}
/// <summary>
/// This can be changed to a complex object instead of just list of strings
/// </summary>
public List<string> FilterCriteria { get; private set; }
public void GetFilterCriteria()
{
if (!OpenFile()) throw new FileLoadException($"Couldn't open the file - {filePath}");
if (wks.AutoFilter == null) return;
// here we get sheet in the workbook.xml (Equals don't work here)
var sheetInWkb = wkb.Workbook.Descendants<Sheet>().Where(s => s.Name == wks.Name).FirstOrDefault();
// get a reference to the worksheet part. Imagine part as the folder in the zip structure
WorksheetPart wsPart = (WorksheetPart)(wkb.GetPartById(sheetInWkb.Id));
// finally get the xml file e.g. sheet1.xml
var sheet = wsPart.Worksheet;
// there should be just one autofilter per sheet
var filter = sheet.Descendants<AutoFilter>().First();
if (filter == null) throw new InvalidOperationException($"Couldn't get autofilter data from the {wks.Name} sheet.");
ManageFilterData(filter);
}
private void ManageFilterData(AutoFilter filter)
{
FilterCriteria = new List<string>();
// this is always the first element in AutoFilter
foreach (FilterColumn filterCol in filter)
{
// here we get the filters data
var filters = filterCol.FirstChild;
if (filters is Filters)
{
foreach (var item in filters)
{
if (item is DateGroupItem)
{
FilterCriteria.Add(GetDateFilterCriteria(item as DateGroupItem));
}
else if (item is Filter)
{
FilterCriteria.Add(((Filter)item).Val);
}
else
{
throw new Exception("Not sure what to do here");
}
}
}
else if (filters is CustomFilters)
{
// if custom filter is applied (more than one criteria it falls to this category
foreach (var item in filters)
{
if (item is CustomFilter)
{
var tmp = item as CustomFilter;
FilterCriteria.Add($"{tmp.Operator}, {tmp.Val}");
}
else
{
throw new Exception("Not sure what to do here");
}
}
}
}
}
private string GetDateFilterCriteria(DateGroupItem criteria)
{
if (criteria.DateTimeGrouping == DateTimeGroupingValues.Year)
{
return criteria.Year.ToString();
}
else if (criteria.DateTimeGrouping == DateTimeGroupingValues.Month)
{
return $"{criteria.Year.ToString()}-{criteria.Month.ToString()}";
}
else if (criteria.DateTimeGrouping == DateTimeGroupingValues.Day)
{
return $"{criteria.Year.ToString()}-{criteria.Month.ToString()}-{criteria.Day.ToString()}";
}
else if (criteria.DateTimeGrouping == DateTimeGroupingValues.Hour)
{
return $"{criteria.Year.ToString()}-{criteria.Month.ToString()}-{criteria.Day.ToString()} {criteria.Hour.ToString()}:00:00";
}
else if (criteria.DateTimeGrouping == DateTimeGroupingValues.Minute)
{
return $"{criteria.Year.ToString()}-{criteria.Month.ToString()}-{criteria.Day.ToString()} {criteria.Hour.ToString()}:{criteria.Minute.ToString()}:00";
}
else
{
return $"{criteria.Year.ToString()}-{criteria.Month.ToString()}-{criteria.Day.ToString()} " +
$"{criteria.Hour.ToString()}:{criteria.Minute.ToString()}:{criteria.Second.ToString()}";
}
}
/// <summary> Opens the given file via the DocumentFormat package </summary>
/// <returns></returns>
private bool OpenFile()
{
try
{
docStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
openXmlDoc = SpreadsheetDocument.Open(docStream, false);
wkb = openXmlDoc.WorkbookPart;
return true;
}
catch (Exception)
{
return false;
}
}
public void Dispose()
{
openXmlDoc?.Close();
docStream?.Close();
}
}
}