如何使用c#从.csv文件中找出特定的行和列值? [英] How to find out specific row and column value from .csv file using c# ?

查看:1813
本文介绍了如何使用c#从.csv文件中找出特定的行和列值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有接受列名的文本框,csv文件的行名称的一个文本框,以及一个按钮,点击按钮我想在其他文本框中显示行和列的特定值,

请帮帮我。

谢谢。

sushil



我尝试了什么:



我只能找到列名。

I have textbox which accept the column name, one textbox for row name of csv file, and one button, on button click i want to show the specific value of row and column in other textbox,
please help me.
thank you.
sushil

What I have tried:

I am able to find only column name.

推荐答案

如果你能读(识别CSV文件中的请求列名称,这意味着您已经能够打开CSV文件并以结构化方式阅读 * 。由于行未以标准方式命名或以其他方式明确标识,因此行名称意味着您要在名称列中找到具有特定值的行。因此,您必须像使用其他请求的列一样识别此名称列,然后读取行并停止name列包含请求的行名称的位置。



* :除非你只是在做一个String.Contains(columnName)?然后,您需要使用实际解决方案来读取CSV文件。看看这个:快速CSV阅读器 [ ^ ]



编辑:

使用上面链接的CSVReader解决方案的示例代码。您需要从该解决方案中引用LumenWorks.Framework.IO.dll。我的测试数据是您在名为testdata.csv的文件中的评论中的小样本表:

If you can read (identify) the requested column name in the CSV file that should mean that you are already able to open a CSV file and read it in a structured fashion*. As rows aren't named or otherwise explicitly identified in a standard way, your "row name" implies that you want to find a row that has a specific value in a kind of "name" column. So you have to identify this "name" column like you did with the other requested column and then read through the rows and stop where the "name" column contains the requested row name.

* : Unless you're just doing a String.Contains(columnName) ? Then you need to use an actual solution to read CSV files. Take a look at this one: A Fast CSV Reader[^]


Sample code using the CSVReader-solution linked above. You need to reference the "LumenWorks.Framework.IO.dll" from that solution. My test data was that small sample table from your comment in a file named "testdata.csv":
// required namespaces:
using System.IO;
using LumenWorks.Framework.IO.Csv;

// ----

string nameColumnName = "a";
string valueColumnName = "d";
string rowName = "r";

using (CsvReader csvReader = new CsvReader(new StreamReader(@"..\..\testdata.csv"), hasHeaders: true))
{
    int nameColumnIndex = csvReader.GetFieldIndex(nameColumnName);
    int valueColumnIndex = csvReader.GetFieldIndex(valueColumnName);

    while (csvReader.ReadNextRecord())
    {
        if (csvReader[nameColumnIndex] == rowName)
        {
            string value = csvReader[valueColumnIndex]; // "9"

            // do something with value here

            break;
        }
    }
}


这篇关于如何使用c#从.csv文件中找出特定的行和列值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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