datagrid data from excel

essamce 621 Reputation points
2020-11-26T16:16:33.543+00:00

hi
is there a way to allow DataGrid to accept data paste data from excel, or any other wpf control supprts that?

any help will be apprecited.

Developer technologies | Windows Presentation Foundation
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Castorix31 91,501 Reputation points
    2020-11-26T16:28:58.267+00:00
    1 person found this answer helpful.
    0 comments No comments

  2. DaisyTian-1203 11,651 Reputation points Moderator
    2020-11-27T03:44:10.703+00:00

    Here is my demo for you:
    The xaml code is:

        <Window.Resources>  
            <RoutedUICommand x:Key="PasteFromExcelClick" Text="Paste" />  
        </Window.Resources>  
      
        <Window.InputBindings>  
            <KeyBinding Gesture="Ctrl+V" Command="{StaticResource PasteFromExcelClick}"/>  
        </Window.InputBindings>  
      
        <Window.CommandBindings>  
            <CommandBinding Command="{StaticResource PasteFromExcelClick}"  
                        CanExecute="CommandBinding_PasteFromExcelClick_CanExecute"  
                        Executed="CommandBinding_PasteFromExcelClick_Executed"/>  
        </Window.CommandBindings>  
        <Grid>  
            <DataGrid x:Name="dataGrid" ItemsSource="{Binding }"  AutoGenerateColumns="False"  
                                       SelectionUnit="FullRow"  
                                       SelectionMode="Extended" Width="400" >  
                <DataGrid.Columns>  
                    <DataGridTextColumn Header="Name" Width="80" Binding="{Binding Name}"/>  
                    <DataGridTextColumn Header="Age" Width="50" Binding="{Binding Age}" />  
                    <DataGridHyperlinkColumn Header="Email" Width="150"  Binding="{Binding Email}"/>  
                </DataGrid.Columns>  
            </DataGrid>  
        </Grid>  
    

    The cs code is :

     public partial class MainWindow : Window  
        {  
            ObservableCollection<Member> memberData = new ObservableCollection<Member>();  
            public MainWindow()  
            {  
                InitializeComponent();  
                Random radom = new Random();  
      
                for (int i = 1; i < 12; i++)  
                {  
                    Member men = new Member();  
                    men.Age = radom.Next(100).ToString();  
                    men.Name = "JOE" + i.ToString();  
                    men.Email ="mailto:JOE" + i.ToString() + "+@school.com";  
                    memberData.Add(men);  
                }  
                dataGrid.DataContext = memberData;  
            }  
            private void CommandBinding_PasteFromExcelClick_CanExecute(object sender, CanExecuteRoutedEventArgs e)  
            {  
                e.CanExecute = true;  
            }  
      
            private void CommandBinding_PasteFromExcelClick_Executed(object sender, ExecutedRoutedEventArgs e)  
            {  
                var clipboardContent = Clipboard.GetText();  
      
                if (string.IsNullOrEmpty(clipboardContent)) return;  
                var rows = clipboardContent  
                    .Split(new string[] { "\r\n" }, StringSplitOptions.None)  
                    .Where(x => !string.IsNullOrEmpty(x))  
                    .ToList();  
      
               int selectedIndex = this.dataGrid.SelectedIndex;  
               if(selectedIndex == dataGrid.Items.Count-1)//Paste to the last row  
               {  
                    foreach (var row in rows)  
                    {  
                        var columns = row.Split('\t');  
                        if (columns.Count() < 3)  
                        {  
                            MessageBox.Show("Please select 3 columns in Excel.", "Clipboard content incorrect", MessageBoxButton.OK, MessageBoxImage.Exclamation);  
                            return;  
                        }  
                        var member = new Member  
                        {  
                            Name = columns[0],  
                            Age = columns[1],  
                            Email = columns[2]  
                        };  
      
                        this.memberData.Add(member);  
                    }  
               }  
               else // paste items to replace the selected rows  
               {  
                    int cIndex = -1;  
                    int rIndex = -1;  
                    if (dataGrid.SelectedCells.Count > 0)  
                    {  
                        int i = this.dataGrid.SelectedIndex;  
                        DataGridCellInfo dgcInfo = dataGrid.SelectedCells[0];  
                        cIndex = dgcInfo.Column.DisplayIndex;  
                        Member dii = dgcInfo.Item as Member;  
                        rIndex = GetMemberIndex(dii);  
                        Console.WriteLine("(" + cIndex.ToString() + "," + rIndex.ToString() + ")");  
                    }  
                    string[] Rinfo = clipboardContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);  
                    //if (cIndex > -1 && rIndex > -1)  
                    {  
                        int rSum = Math.Min(Rinfo.Length, dataGrid.Items.Count - rIndex);  
                        for (int i = 0; i < rSum; i++)  
                        {  
                            string[] Cinfo = Rinfo[i].Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);  
                            int cSum = Math.Min(Cinfo.Length, dataGrid.Columns.Count - cIndex);  
                            for (int j = 0; j < cSum; j++)  
                            {  
                                DataGridColumn dgcC = dataGrid.Columns[cIndex + j];  
                                try  
                                {  
                                    (dataGrid.Columns[cIndex + j].GetCellContent(dataGrid.Items[rIndex + i]) as TextBlock).Text = Cinfo[j];  
                                }  
                                catch  
                                {  
      
                                }  
                            }  
                        }  
                    }  
                }  
            }  
      
            private int GetMemberIndex(Member di)  
            {  
                if (memberData.Contains(di))  
                {  
                    return memberData.IndexOf(di);  
                }  
                else  
                {  
                    return -1;  
                }  
            }  
        }  
      
        public class Member  
        {  
            public string Name { get; set; }  
            public string Age { get; set; }  
            public string Email { get; set; }  
        }  
    

    The result picture is:
    43074-2.gif


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.