[英]Copy Paste from Excel
我正在從Excel復制數據,然后單擊按鈕將其粘貼到Windows窗體。
從excel復制的數據被拆分並填充四個文本框。 所有的texbox都按預期填充,但最后一個文本框得到額外的“ \\ r \\ n”。 它沒有顯示在文本框中,但是如果我設置斷點並查看變量,則會有額外的\\ r \\ n。
我抓取的變量看起來像這個測試\\ r \\ n。
我知道我可以用“”代替,但是有辦法避免這種情況的發生。
這是我的粘貼事件處理程序的代碼。
if (Clipboard.GetText() != null)
{
string s = Clipboard.GetText();
string[] lines = s.Split('\t');
if (lines.Length < 3)
{
DialogResult result = MsgBox.Show("Please copy valid data with tab space.", "Incorrect data format.", MsgBox.Buttons.OK, MsgBox.Icon.Exclamation, MsgBox.AnimateStyle.ZoomIn);
//MessageBox.Show("Please copy valid data with tab space.", "Incorrect data format.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
else
{
green_textBox_ref.Text = lines[0].Replace(" ", "");
green_textBox1.Text = lines[1].Replace(" ", "");
green_textBox2.Text = lines[2].Replace(" ", "");
green_textBox3.Text = lines[3].Replace(" ", "");
green_textBox_ref.Enabled = false;
green_textBox1.Enabled = false;
green_textBox2.Enabled = false;
green_textBox3.Enabled = false;
paste_green.Enabled = false;
}
}
else
{
DialogResult result = MsgBox.Show("There is no data to paste.", "No data", MsgBox.Buttons.OK, MsgBox.Icon.Error, MsgBox.AnimateStyle.ZoomIn);
//MessageBox.Show("There is no data to paste.", "No data", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
這是斷點的屏幕截圖。
您可以通過幾種不同的方式刪除該換行符。 由於已經在分割字符串,因此可以告訴它將換行符作為附加的定界符,並刪除空的子字符串。
string[] lines =
s.Split(new[] {"\t", Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
或者,您可以使用TrimEnd()
修剪掉字符串末尾的特定字符。
green_textBox3.Text = lines[3].Replace(" ", "").TrimEnd('\r', '\n');
我懷疑有一種方法可以防止從Excel復制時將其包含在ClipBoard中。
由於無法避免\\ t,因此無法避免\\ r \\ n。 這就是粘貼客戶端如何使用\\ t \\ r和\\ n了解表格數據的方式。
如果復制的Excel范圍具有多個行,則會得到許多\\ r \\ n。
最好是使用String.Replace
方法刪除\\ r \\ n。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.