我在电子表格中有一些值,如下例所示:
我总是至少有两列(可能很多),而且值之间总是有空行。
我想做什么:复制这两列,粘贴在一个textBox中,当我按下一个按钮时,我希望这个文本的格式如下:
所以,基本上我需要:
是的,我需要的是将excel表转换为Java Script矩阵,以便在Selenium Web浏览器自动化上使用。
我已经做了一个帮助我很多的代码,但只需要在excel中使用一个列,将其转换为简单的javascript向量,这里是代码:
String[] vector = textBox1.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
String vectorFinal = String.Join("','", vector);
textBox2.Text = "'" + vectorFinal + "'";
Clipboard.SetText(textBox2.Text);
我刚刚开始研究C#,这就是为什么我仍然不知道如何去做。处理多个列涉及让我疯狂的TAB字符哈哈...提前感谢!
答案 0 :(得分:0)
兄弟..让我们循环进入这些excel行,并尝试验证行是否为空...对于每个非空行,我们应该再用TAB字符拆分它(你必须注意到当您从Excel中复制时,它会通过TAB分隔列... ...让您从第一个变量“vector”开始工作:
//First, you are splitting your text by a line break. Each array position is one Excel line:
String[] vector = textBox1.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
String vectorFinal = ""; //empty string, lets add values here later
foreach(String excelLine in vector)
{
if (!excelLine.Trim().Equals("")) //if the line is not only empty chars...
{
//split the line (ex: "AAAAA 1111" by the TAB character between AAAA and 1111, which is the Excel way to separate the columns. \t is the Regex code for TAB)
String[] excelColumns = excelLine.Split(new String[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
//and add it to your final string: add a new line to the string, starts with [ and '... and ends with ... ' and ]:
vectorFinal += Environment.NewLine + "['" + String.Join("','", excelColumns) + "'],";
}
}
//now, just set your textbox text!
textBox2.Text = vectorFinal;
Clipboard.SetText(textBox2.Text);
顺便说一句......上面的源代码会创建一个这样的字符串: ['AAAA','1111'], ['BBBB','2222'],
..注意到最后一个逗号?你可能不希望它在那里.. 更专业的解决方案是将String vectorFinal变量替换为List,如下所示:
List<String> vectorFinal = new List<String>();
..这样你可以将值添加到此List,而不是“vectorFinal + = ...”(暂时忽略NewLine):
vectorFinal.Add("['" + String.Join("','", excelColumns) + "]");
最后,当您设置textbox2文本时,只需执行一个新的String.Join:
//join the last array, separating its values for a new line and comma:
textBox2.Text = String.Join("," + Environment.NewLine, vectorFinal);