【问题标题】:How to read data from an excel and push into an array in asp.net?如何从 excel 中读取数据并推入 asp.net 中的数组?
【发布时间】:2021-05-26 23:20:05
【问题描述】:

我是 C# 编程的新手,想知道如何从 Excel 中逐个单元格地读取数据。在下面的代码中,我从 excel 的 A 列中获取一组数据,如 pValue1= a;b;c;d%;e%;f%;现在,如果列 A=ID 的标题,我只想将末尾带有 % 的值推送到不同的数组中。另外,我想用单引号将 pValue1 中的每个项目括起来。

输入:

ID Name
a roy
b may
c Jly
d% nav
e% nov
f% lio

预期输出: pValue1='a';'b';'c' pValue3= d%e%f%

         try {
                Utils.ExcelFile excelFile = new Utils.ExcelFile(excelFilename);
                DataTable excelData = excelFile.GetDataFromExcel();

                // Column headers
                param1 = 0 < excelData.Columns.Count ? excelData.Columns[0].ColumnName :string.Empty;
                param2 = 1 < excelData.Columns.Count ? excelData.Columns[1].ColumnName :string.Empty;

                ArrayList pValueArray1 = new ArrayList();
                ArrayList pValueArray2 = new ArrayList();

                if (pValueArray1.Count > 0) pValue1 = string.Join(";", pValueArray1.ToArray()) + ";";
                if (pValueArray2.Count > 0) pValue2 = string.Join(";", pValueArray2.ToArray()) + ";";
               
            }

【问题讨论】:

    标签: c# asp.net arrays excel


    【解决方案1】:

    不确定我是否理解您的问题。我猜您已经将 excel 加载到 DataTable 中,而您现在只想将 Id-column 拆分为两个单独的列表。您可以使用 LINQ:

    var percentLookup = excelData.AsEnumerable()
        .ToLookup(row => row.Field<string>("Id").EndsWith("%"));
    List<string> pValue1List = percentLookup[false]
        .Select(row => row.Field<string>("Id"))
        .ToList();
    List<string> pValue2List = percentLookup[true]
        .Select(row => row.Field<string>("Id"))
        .ToList();
    

    查找包含两个组,id 列末尾有百分比的行和其余行。因此,您可以使用它轻松创建两个列表。

    由于您是 C# 编程新手,因此使用普通循环可能会更好:

    List<string> pValue1List = new List<string>();
    List<string> pValue2List = new List<string>();
    foreach (DataRow row in excelData.Rows)
    {
        string id = row.Field<string>("Id");
        if(id.EndsWith("%"))
        {
            pValue2List.Add(id);
        }
        else
        {
            pValue1List.Add(id);
        }
    }
    

    如果您需要String[] 而不是List&lt;string&gt;,请使用ToArray 而不是ToList,在第二种方法中填写列表,但最后使用pValue1List.ToArray

    一般来说:您应该停止使用 ArrayList,它已有 20 年的历史,并且已经过时了 10 多年。使用强类型的List&lt;T&gt;,这里是List&lt;string&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      相关资源
      最近更新 更多