How to Import/Export data of DataGrid from/to CSV file in wpf using MVVM

In this post i will explain how to Import/Export data of DataGrid from/to CSV file in wpf using MVVM

To Import CSV to DataGrid i have created method called LoadCSV() which will load CSV data and update the DataGrid


 private void LoadCSV()

        {

            LstEmployees.AddRange(File.ReadAllLines("csvFilePath")

                                         .Skip(1)

                                         .Select(v => CsvToEmployees(v))

                                         .ToList());


        }

        

In LoadCSV() method i am first reading the CSV using File clas ReadAllLines() method

After that i am skip the first line becuase in first line we used to have Header for CSV file

And then i am calling CsvToEmployees() which take a single line and split the text by comma and then convert it to Employees.

After converting All text to Employees list i am adding the list to ObservableCollection which is Binded with DataGrid


        Employees CsvToEmployees(string csvLine)

        {

            var emp = new Employees();

            if(!string.IsNullOrEmpty(csvLine))

            {

                string[] values = csvLine.Split(',');

                emp.EmpId = Convert.ToInt32(values[0]);

                emp.EmpName = values[1];

                emp.JobTitle = values[2];

                emp.Experience = values[3];

                emp.Salary = Convert.ToDouble(values[4]);

            }

            return emp;

        }

        

To Export DataGrid data to CSV i have added command called ExportCommand which will bind to Export Button in View


 private DelegateCommand _exportCommand;

        public DelegateCommand ExportCommand =>

            _exportCommand ?? (_exportCommand = new DelegateCommand(Export));


        private void Export()

        {

            using(var sw = new StreamWriter("CSVPath")

            {

                string header = String.Join(",", "Emp Id", "Emp Name", "Jop Title", "Experience", "Salary");

                sw.Write($"{header}{Environment.NewLine}");

                foreach(var emp in LstEmployees)

                {

                    string csv = String.Join(",", emp.EmpId, emp.EmpName,emp.JobTitle, emp.Experience, emp.Salary);

                    sw.Write($"{csv}{Environment.NewLine}");


                }

            }

        }    


In Export() method i am using StreamWriter to write to the CSV file.

For the Header i created the string with comma seperated Header text and call the Write() method to Write header to CSV file.

After That i am iterating the LstEmployees and make the comma seperated string with employee value and again call the Write() method to Write data to CSV file.


check this link for the code

Comments

Popular posts from this blog

Pagination of DataGrid in WPF using MVVM

Filter DataGrid and ListView in wpf using ICollectionView

Connect SQL Server Database to WPF Application and Perform CRUD Operations