Pasting excel data into a blank DataGridView - Index out of range exception

前端 未结 8 1511
不思量自难忘°
不思量自难忘° 2020-12-30 07:20

I have an excel sheet with the following:

\"enter

So, what I am trying to achi

8条回答
  •  灰色年华
    2020-12-30 07:59

    //Column Count Bug Propered:://

    using System.Linq;
    
    DataTable xDataTable = new DataTable();
    DataObject XClipboardDat = (DataObject)Clipboard.GetDataObject();
    
    if (XClipboardDat.GetDataPresent(DataFormats.Text))
    {
        string[] XClipboardRows = Regex.Split(XClipboardDat.GetData(DataFormats.Text).ToString(), @"[\r\n]+").Where(y => !string.IsNullOrEmpty(y.ToString())).ToArray();
    
        IEnumerable XDatRowCol = XClipboardRows.Select(xRow => Regex.Split(xRow, @"[\t]+").Where(y => !string.IsNullOrEmpty(y.ToString())).ToArray());
    
        int ColNum = XDatRowCol.Select(XDatRow => XDatRow.Length).ToArray().Max();
    
        for (int i = 0; i < ColNum; i++) { xDataTable.Columns.Add(); }
    
        foreach(string[] XDatRow in XDatRowCol) { xDataTable.Rows.Add(XDatRow); }
    
        dataGridView2.DataSource = xDataTable;
     }
    

提交回复
热议问题