我如何使用c#迭代excel单元格? [英] How do I. iterate through excel cells using c#?

查看:60
本文介绍了我如何使用c#迭代excel单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何使用C#迭代excel单元格。



我有一个数据表,用于将数据导出到现有的Excel文件。我需要能够搜索仅等于tel:和email:的值。这些值只会出现在excel的第二列。



这是我的代码序列。请让我知道我做错了什么或者有更好的方法。



I need to know how to iterate through excel cells using C#.

I have a Data Table that I use to export data to an existing Excel file. I need to be able to search for values that only equal "tel:" and "email:". These values will only be in the second column in excel.

Here is my code sequence. Please let me know what I am doing wrong or if there is a better way.

int rowNum = 1;

foreach (Microsoft.Office.Interop.Excel.Range cell in ws.Rows[rowNum, 2])
     {
         if (cell.Value = "tel:")
         {
        ws.Rows[rowNum].Delete();
         }
     }

推荐答案

在这里你去



pre requisite - 安装AccessDatabaseEngine 2007或2007



here you go

pre requisite- Install AccessDatabaseEngine 2007 or 2007

try
{
string path; // your file path 

oledbConn =
    new OleDbConnection(
        @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path
        + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");

oledbConn.Open();
var cmd = new OleDbCommand();

var ds = new DataSet();
cmd.Connection = oledbConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELEet1


& amp; quot ;;工作表名称
var oleda = new OleDbDataAdapter(cmd);
oleda.Fill(ds);

foreach(数据行在ds.T ?? les [0]。行)
{
// TODO
}
catch(Exception ex )
{
//记录它
}
最后
{
oledbConn.Close();
}
"; Name of sheet var oleda = new OleDbDataAdapter(cmd); oleda.Fill(ds); foreach (DataRow row in ds.T??les[0].Rows) { // TODO } catch (Exception ex) { // log it } finally { oledbConn.Close(); }


您还可以使用oledb逐个单元格读取/写入,而不是使用互操作(office组件)。
You can also use oledb to read/write cell by cell values instead of using interop(office component).


这篇关于我如何使用c#迭代excel单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆