[英]Find column from row 1 header, and get column number (Excel.interop?
If I have an excelsheet like 如果我有一个像
Name, age, ID; 姓名,年龄,身份证;
Peter, 35, 123456; 彼得,35岁,123456;
Is there a way for me to locate that age is column numner 2, by searching for age in row 1, or similar? 我是否可以通过搜索第1行或类似的年龄来确定年龄是第2列年龄?
What you can do is iterate through every column in the excel sheet and create a dictionary for every name/value pair. 您可以做的是遍历excel工作表中的每一列,并为每个名称/值对创建一个字典。 For example, 0 would map to Name, 1 would map to age and 2 would map to ID. 例如,0将映射到Name,1将映射到age,而2将映射到ID。 From here, you may iterate through each row and for each column in that row look-up the name value pair (based on column ID). 从这里开始,您可以遍历每一行,并针对该行中的每一列查找名称/值对(基于列ID)。 From there, you'll be able to determine the age. 从那里,您可以确定年龄。
Is there a way for me to locate that age is column numner 2, by searching for age in row 1, or similar?
Yes. 是。 Assuming the rows are really kept in the format you specified, separated by a comma, you can easily use string's Split method, and Linq's Select method: 假设行确实保持您指定的格式,并用逗号分隔,则可以轻松使用字符串的Split方法和Linq的Select方法:
string row = "Name, age, ID";
int columnNum = Array.IndexOf(row.Split(',')
.Select(x => x.Trim()).ToArray(), "age") + 1;
Explanation: 说明:
row.Split(',')
- this method splits the string into an Array of strings: { "Name", "age", "ID" } row.Split(',')
-此方法将字符串拆分为字符串数组:{“ Name”,“ age”,“ ID”}
.Select(x => x.Trim()).ToArray()
- this expression use LINQ to eliminate all the unnecessary spaces in the column Name (the method Trim() removes spaces at the beginning and at the end of the string). .Select(x => x.Trim()).ToArray()
-此表达式使用LINQ消除列Name中的所有不必要空格(方法Trim()删除字符串开头和结尾的空格) 。
Array.IndexOf
- This method finds the index of the desired value ("age") within the array. Array.IndexOf
此方法在数组中查找所需值(“ age”)的索引。
Indexes in C# begins at zero. C#中的索引从零开始。 namely, the index of "Name" is 0, and the index of "age" is actually 1 (and so on). 也就是说,“名称”的索引为0,而“年龄”的索引实际上为1(依此类推)。 To solve this I simply add 1 to the number returned by "IndexOf". 为了解决这个问题,我只需在“ IndexOf”返回的数字上加1。
I'm warmly recommend to read any C# basic tutorial. 我热烈建议阅读任何C#基础教程。 it's all there :) 都在那里:)
从MSDN中检查Excel中的字符串搜索示例: http : //msdn.microsoft.com/zh-cn/library/e4x1k99a.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.