如何通过c#筛选excel里的指定内容
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何通过c#筛选excel里的指定内容相关的知识,希望对你有一定的参考价值。
//那就全部读到datatable里,然后在判断using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using Microsoft.Office.Interop.Excel;
namespace TestAccess
class Program
static void Main(string[] args)
string strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;";
strConnection += @"Data Source=C:\\Documents and Settings\\v-changl\\My Documents\\couse.xlsx;";
strConnection += "Extended Properties=\\"Excel 12.0 Xml;HDR=YES\\";";
OleDbConnection objConnection = new OleDbConnection(strConnection);
objConnection.Open();
OleDbDataAdapter myCommandd = new OleDbDataAdapter("select * from [Sheet1$]", objConnection);
DataSet ds = new DataSet();
myCommandd.Fill(ds, "[Sheet1$]");
System.Data.DataTable dt = ds.Tables["[Sheet1$]"];
Console.WriteLine(dt.Columns[0].ToString());
Console.WriteLine(dt.Columns[1].ToString());
DataRow drDisplay = dt.Rows[0];
int[] num = new int[dt.Columns.Count];
for (int j = 0; ; )
for (int i = 0; i < dt.Columns.Count; i++)
if (drDisplay[i] is DBNull) ;
else
num[i] += Convert.ToInt32(drDisplay[i]);
if (++j >= dt.Rows.Count) break;
drDisplay = dt.Rows[j];
objConnection.Close();
object MissingValue = Type.Missing;
Microsoft.Office.Interop.Excel.Application app = new Application();
Microsoft.Office.Interop.Excel.Workbook wbook = app.Workbooks.Open(@"C:\\Documents and Settings\\v-changl\\My Documents\\couse.xlsx", MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue);
Microsoft.Office.Interop.Excel.Worksheet wsheet = wbook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
for (int i = 0; i < dt.Columns.Count; i++)
//注意下面是i+1,,excel小标默认从1开始
wsheet.Cells[dt.Rows.Count + 2, i + 1] = num[i].ToString();
wbook.Save();
wbook.Close(true, null, null);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wsheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
wsheet = null;
wbook = null;
app = null;
GC.Collect();
参考技术A
参考以下更为简洁的方法(需要引用Spire.XLS.dll)
//创建Workbook对象Workbook workbook = new Workbook();
//加载现有的Excel文档
workbook.LoadFromFile(@"C:\\Users\\Administrator\\Desktop\\sample.xlsx");
//获取第一个工作表
Worksheet sheet = workbook.Worksheets[0];
//获取筛选器对象
AutoFiltersCollection filters = sheet.AutoFilters;
//设置筛选器的添加位置:第二列
filters.Range = sheet.Range[1, 2, sheet.LastRow, 2];
//添加筛选项目
filters.AddFilter(0, "测试");
//执行筛选f
ilters.Filter();
//保存文档
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2010);
执行程序后,筛选效果如下:
可参考原文
以上是关于如何通过c#筛选excel里的指定内容的主要内容,如果未能解决你的问题,请参考以下文章