Excel数据复制到Winform控件ListView

  1. 先给窗体添加一个右键菜单contextMenuStrip
  2. 加一个下拉项【粘贴】
  3. 粘贴事件:
 private void tsmiPaste_Click(object sender, EventArgs e)
        {
            listViewData.Items.Clear();
            listViewData.Columns.Clear();
            listViewData.Columns.Add("", 0, HorizontalAlignment.Center);
            listViewData.Columns.Add("序号", 40, HorizontalAlignment.Right);
            listViewData.Columns.Add("快递单号", 120, HorizontalAlignment.Center);
            listViewData.Columns.Add("修改重量", 80, HorizontalAlignment.Right);

            var i = 0;
            var strShuju = ""; //取得的字符串
            IDataObject iData = Clipboard.GetDataObject();
            if (iData.GetDataPresent(DataFormats.Text))
            {
                strShuju = (string)iData.GetData(DataFormats.Text);
            }
            if (strShuju.IndexOf("\r\n") == -1) return;
            var iShuju = strShuju.Length; //字符串总长度
            while (strShuju != "")
            {
                try
                {
                    var myItem = new ListViewItem();
                    myItem.SubItems.Add((++i).ToString());
                    var strRow = strShuju.Substring(0, strShuju.IndexOf("\r\n")); // 每行字符串
                    var iRow = strShuju.Substring(0, strShuju.IndexOf("\r\n")).Length; //每行字符串长度

                    var iRow1 = 0; //每行字符串长度
                    if (iRow == 0)
                        break;
                    iRow1 = iRow + 1;
                    iRow = iRow + 2;
                    iShuju = iShuju - iRow;
                    strShuju = strShuju.Substring(iRow, iShuju);
                    strRow = strRow + "\t";

                    while (strRow != "")
                    {
                        var strColumn = strRow.Substring(0, strRow.IndexOf("\t")); //每段字符串
                        var iColumn = strColumn.Substring(0, strRow.IndexOf("\t")).Length; //每段字符串长度
                        if (iRow1 == 0)
                            break;
                        iRow1 = iRow1 - iColumn - 1;
                        strRow = strRow.Substring(iColumn + 1, iRow1);
                        myItem.SubItems.Add(strColumn);
                    }
                    listViewData.Items.Add(myItem);
                }
                catch (ArgumentOutOfRangeException)
                {
                    break;
                }
            }
        }

 

posted @ 2015-05-06 10:40  奇风★逍遥  阅读(1324)  评论(0编辑  收藏  举报