How to import and export CSV files using WPF?

In this blog, we will be going to discuss how to import and export CSV files using WPF. WPF abbreviated as Windows Presentation Foundation is a User Interface framework for creating the desktop application with astonishing styles and templates.

WPF development platform supports broad application development features in the application model, resource, controls, 2D and 3D graphics, layout, data binding, templates, documents, media, text, and security.

WPF is a part of the .Net framework, so you have previously built-in applications with .NET using Asp.Net. WPF uses the Extensible Application Markup Language (XAML).

How to create a CSV File?

Please follow these steps to create a CSV file.

Step 1: First create an Excel file.

Step 2: Insert the data in Excel file.

Step 3: After inserting the data, the excel file saves and assigns the name as DemoFile.xlsx this file is called an Excel file.

How to import and export CSV files using WPF
create csv file wpf application

Step 4: After creating the Excel file now you have to click the menu button and click the Save As button then assign the name and extension use the .csv file. .csv is an extension of CSV file.  

read csv file in wpf
Save the file as DemoFile.csv

How to import and export CSV file using CSV library in WPF?

  • CSV full form is Comma Separated value. A CSV file is a text file of a specific format that allows you to save data in a structured table format.
  • In a WPF application, we will show you the basic import or export processing using our own library of small CSV Import or Export CSV files in a 32-bit machine.

Prerequisites

These are some prerequisites.

  1. First install the CSVLibraryAK NuGet package in your project.
  2. Basic Knowledge about Windows Platform Form (WPF).
  3. Basic Knowledge about C# Programming and .NET framework.
  4. Basic knowledge about C# LINQ. 

Please follow these steps to import and export CSV file using CSV Library in WPF.

Step 1: First Create a new project for the WPF application and select the template of the .NET core.

Step 2: After creating the project install the package of CSVLibraryAk NuGet package in the project.

Install CSVLibraryAk NuGet package
Install CSVLibraryAk NuGet package

Step 3: After installing the package you have to create a XAML file for import and export to CSV file.

File Name: MainWIndow.xaml

Code:

<Window x:Class="ImportExportDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ImportExportDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel Grid.Row="0"    
                                Orientation="Horizontal"    
                                VerticalAlignment="Center"    
                                HorizontalAlignment="Center"    
                                Margin="0,10,0,0">

            <!-- Export button -->
            <Button x:Name="export_to_csvFile"     
                            Click="ExportBtn_Click"    
                            ToolTip="Export to CSVFile"    
                            Margin="0,0,20,0">

                <Image Source="/WPFImportExportCSV;component/Content/img/export.png" Width="50" Height="50"/>
            </Button>

            <Border x:Name="csvFileBr"    
                                            CornerRadius="8.5"     
                                            BorderThickness="0"    
                                            Width="300"    
                                            Height="40"    
                                            SnapsToDevicePixels="True"    
                                            Opacity="1">

                <Border.Background>
                    <ImageBrush ImageSource="/WPFImportExportCSV;component/Content/img/text-box_bg.png"/>
                </Border.Background>

                <TextBox x:Name="csvFilePath"    
                                         Width="400"     
                                         Height="40"    
                                         FontSize="14"      
                                         HorizontalAlignment="Center"     
                                         VerticalAlignment="Top"     
                                         IsEnabled="true"     
                                         BorderThickness="0"    
                                         VerticalContentAlignment="Center"    
                                         Padding="20,0,0,0"    
                                         Background="Transparent"    
                                         Foreground="Black" />
            </Border>

            <Button x:Name="Browsebtn"    
                                Content="..."     
                                Foreground="Black"    
                                Margin="5,0,0,0"    
                                Height="30"    
                                Width="50"     
                                Padding="0,0,0,0"    
                                HorizontalAlignment="Left"     
                                VerticalAlignment="Center"    
                                Click="BrowseBtn_Click"     
                                FontSize="18"     
                                FontWeight="Bold" />

            <CheckBox x:Name="chekHasHeader"    
                                  Content="First row Column name is"    
                                  IsChecked="True"    
                                  VerticalAlignment="Center"    
                                  HorizontalAlignment="Center"    
                                  Margin="20,0,0,0"/>
        </StackPanel>

        <DataGrid Grid.Row="1"    
                              x:Name="grdLoading"     
                              AutoGenerateColumns="True"    
                              IsReadOnly="true"    
                              CanUserAddRows="False"    
                              CanUserDeleteRows="False"    
                              CanUserResizeRows="True"    
                              CanUserSortColumns="False"    
                              CanUserResizeColumns="True"      
                              CanUserReorderColumns="False"    
                              SelectionMode="Extended"    
                              SelectionUnit="Cell"    
                              AlternationCount="2"    
                              Background="{x:Null}"                           
                              BorderBrush="{x:Null}"  >
        </DataGrid>

    </Grid>
</Window>

Step 4: Create two methods for Export and Import the CSV file in the project. This code writes in the class file of the Xaml page.

Import and export click event:

File Name:Mainpage.xaml.cs

Code:

using Microsoft.VisualBasic;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ImportExportDemo
{
    public partial class MainWindow : Window
    {
        private DataTable dataTableObj;

        public MainWindow()
        {
            InitializeComponent();
        }
        /// Browse click button event method.  
        private void BrowseBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog browseDialog = new OpenFileDialog();
                DataTable datatable = new DataTable();

                Nullable<bool> result = browseDialog.ShowDialog();
              
                if (browseDialog.ShowDialog() == true)
                {
                    this.csvFilePath.Text = browseDialog.FileName;

                    string filePath = this.csvFilePath.Text;
                    bool isExist = this.chekHasHeader.IsChecked.Value;

                    //Import csv file
                    datatable = CSVLibraryAK.Core.CSVLibraryAK.Import(filePath, isExist);
                    if (datatable.Rows.Count <= 0)
                    {
                        //Show the message for corrupt the data and invalid CSV file    
                        MessageBox.Show("Your file is either corrupt or does not contain any data. Make sure that you are using valid CSV file.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);

                        return;
                    }

                    this.grdLoading.ItemsSource = datatable.DefaultView;

                    this.dataTableObj = datatable;
                }
            }
            catch (Exception ex)
            {
                //show the message for error
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Console.Write(ex);
            }
        }
        /// Export click event method.  
         private void ExportBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.dataTableObj.Rows.Count <= 0)
                {
                    //show the message box for data not available in export file
                    MessageBox.Show("There is no data available to export.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);

                    return;
                }
                
                SaveFileDialog exportDialog = new SaveFileDialog();

         
                Nullable<bool> result = exportDialog.ShowDialog();

                if (exportDialog.ShowDialog() == true)
                {
                    //Export csv file
                    CSVLibraryAK.Core.CSVLibraryAK.Export(exportDialog.FileName, dataTableObj);
                    //show the message for data successfully exported
                    MessageBox.Show("Data has been sucessfully exported in CSV file", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Console.Write(ex);
            }
         }
    }
}

In the above code, we created the “BrowseBtn_Click (…)” method which will take the input from the end-user CSV file and import the CSV file using the CSVLibraryAK library method. (…). Next, process the CSV file and load the resulting data from the CSV file into the WPF DataGrid control.

We have created an “ExportBtn_Click (…)” method to export the DataGrid data to a CSV file using the method in the CSVLibraryAK.Export (…) library. The end-user then stores the CSV file in its destination location.

You may like the following .Net tutorials:

Conclusion

In this blog, we have explained how to import and export the CSV file using CSVLibrary in the WPF application.

CSV abbreviated as Comma Separated Value is a CSV file which is also a text file of a specific format that allows you to save data in a structured table format. If you create a project for import and export the CSV file in your WPF application, firstly you have to install the package of CSVLibraryAK in your application from manage NuGet packages.

CSVLibraryAk library is useful for import and export CSV files. You will also learn about how to import a CSV file using the CSVLibraryAK.Import method and also learn how to import the CSV file to its destination location on your desktop using the CSVLibraryAK.Export() method.

>