VSTO;) SQL Excel. , VSTO API- Excel. ADODB/OLEDB Excel, Autofilter Excel, SpecialCells , Value .
VSTO 2010, 58k , "aba", "cat", "zon".
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.Office.Tools.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
namespace ExcelWorkbook1
{
public partial class ThisWorkbook
{
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
const int Sheet1 = 1;
const int ColumnB = 2;
List<List<object>> results = Query(Sheet1, ColumnB, "aba", "cat", "zon");
foreach (List<object> record in results)
{
System.Diagnostics.Debug.Print("{0,-10} {1,30} {2}", record[0], record[1], record[2]);
}
}
private void ThisWorkbook_Shutdown(object sender, System.EventArgs e)
{
}
private void ClearFilter(Microsoft.Office.Interop.Excel._Worksheet worksheet)
{
if (worksheet.AutoFilter != null)
{
worksheet.Cells.AutoFilter();
}
}
private void ApplyFilter(Microsoft.Office.Interop.Excel._Worksheet worksheet, int column, params string[] predicates)
{
string[] criteria = new string[predicates.Length];
int i = 0;
ClearFilter(worksheet);
foreach (string value in predicates)
{
criteria[i++] = String.Concat("=*", value, "*");
}
worksheet.Cells.AutoFilter(column, criteria, Excel.XlAutoFilterOperator.xlOr);
}
private List<List<object>> Query(int sheetIndex, int columnIndex, params string[] words)
{
Microsoft.Office.Interop.Excel._Worksheet worksheet;
Excel.Range range;
List<List<object>> records = new List<List<object>>();
List<object> record;
object[,] cells;
object value;
int row, column, rows, columns;
bool hit;
try
{
worksheet = (Microsoft.Office.Interop.Excel._Worksheet)Globals.ThisWorkbook.Sheets[sheetIndex];
if (null == worksheet)
{
return null;
}
ApplyFilter(worksheet, columnIndex, words);
range = worksheet.Range["$A:$C"].SpecialCells(Excel.XlCellType.xlCellTypeVisible);
foreach (Excel.Range subrange in range.Areas)
{
cells = subrange.Value;
for (row = cells.GetLowerBound(0), rows = cells.GetUpperBound(0); row <= rows; row++)
{
record = new List<object>();
hit = false;
for (column = cells.GetLowerBound(1), columns = cells.GetUpperBound(1); column <= columns; column++)
{
value = cells[row, column];
hit = hit || (null != value);
if (hit)
{
record.Add(cells[row, column]);
}
}
if (hit)
{
records.Add(record);
}
}
}
}
catch { }
finally
{
cells = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
return records;
}
#region VSTO Designer generated code
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisWorkbook_Startup);
this.Shutdown += new System.EventHandler(ThisWorkbook_Shutdown);
}
#endregion
}
}