WPF - Import/Export CSV File

In a WPF application, I will be demonstrating the basic import/export operations using my own small import/export CSV file library CSVLibraryAK, which is compatible with any C#.NET project of the 32-bit machine. The code of the library is open source. So, anyone can compile the code to target the bit machine or to make new changes.
 
Today, I shall be demonstrating the integration of CSVLibraryAK C#.NET library with WPF platform.
 
 

Prerequisites

 
Following are some prerequisites before you proceed any further in this tutorial.
  1. Install CSVLibraryAK NuGet Package.
  2. Knowledge about Windows Presentation Form (WPF).
  3. Knowledge of C# Programming.
  4. Knowledge about C# LINQ.
You can download the complete source code for this tutorial. The sample code is being developed in Microsoft Visual Studio 2017 Professional.
 
Let's begin now.
 
Step 1
 
Create a new MVC web project and name it "WPFImportExportCSV". 
 
Step 2
 
Create a new "Views\Pages\HomePage.xaml" file and add an export button control, browse button control, a checkbox to determine CSV file header and a DataGrid control. 
  1. ...    
  2.     
  3.                <StackPanel Grid.Row="0"    
  4.                                 Orientation="Horizontal"    
  5.                                 VerticalAlignment="Center"    
  6.                                 HorizontalAlignment="Center"    
  7.                                 Margin="0,10,0,0">    
  8.     
  9.                     <!-- Export button -->    
  10.                     <Button x:Name="export_to_csv"     
  11.                             Click="Export_Click"    
  12.                             ToolTip="Export to CSV"    
  13.                             Margin="0,0,20,0">    
  14.     
  15.                         <Image Source="/WPFImportExportCSV;component/Content/img/export.png" Width="50" Height="50"/>    
  16.                     </Button>    
  17.     
  18.                     <Border x:Name="txtFileBr"    
  19.                                             CornerRadius="8.5"     
  20.                                             BorderThickness="0"    
  21.                                             Width="300"    
  22.                                             Height="40"    
  23.                                             SnapsToDevicePixels="True"    
  24.                                             Opacity="1">    
  25.     
  26.                         <Border.Background>    
  27.                             <ImageBrush ImageSource="/WPFImportExportCSV;component/Content/img/text-box_bg.png"/>    
  28.                         </Border.Background>    
  29.     
  30.                         <TextBox x:Name="txtFilePath"    
  31.                                          Width="400"     
  32.                                          Height="40"    
  33.                                          FontSize="14"      
  34.                                          HorizontalAlignment="Center"     
  35.                                          VerticalAlignment="Top"     
  36.                                          IsEnabled="true"     
  37.                                          BorderThickness="0"    
  38.                                          VerticalContentAlignment="Center"    
  39.                                          Padding="20,0,0,0"    
  40.                                          Background="Transparent"    
  41.                                          Foreground="Black" />    
  42.                     </Border>    
  43.     
  44.                     <Button x:Name="btnBrowse"    
  45.                                 Content="..."     
  46.                                 Foreground="Black"    
  47.                                 Margin="5,0,0,0"    
  48.                                 Height="30"    
  49.                                 Width="50"     
  50.                                 Padding="0,0,0,0"    
  51.                                 HorizontalAlignment="Left"     
  52.                                 VerticalAlignment="Center"    
  53.                                 Click="BtnBrowse_Click"     
  54.                                 FontSize="18"     
  55.                                 FontWeight="Bold" />    
  56.     
  57.                     <CheckBox x:Name="chkHasHeader"    
  58.                                   Content="First row is Column name"    
  59.                                   IsChecked="True"    
  60.                                   VerticalAlignment="Center"    
  61.                                   HorizontalAlignment="Center"    
  62.                                   Margin="20,0,0,0"/>    
  63.                 </StackPanel>    
  64.     
  65.                 <DataGrid Grid.Row="1"    
  66.                               x:Name="grdLoad"     
  67.                               AutoGenerateColumns="True"    
  68.                               IsReadOnly="true"    
  69.                               CanUserAddRows="False"    
  70.                               CanUserDeleteRows="False"    
  71.                               CanUserResizeRows="True"    
  72.                               CanUserSortColumns="False"    
  73.                               CanUserResizeColumns="True"      
  74.                               CanUserReorderColumns="False"    
  75.                               SelectionMode="Extended"    
  76.                               SelectionUnit="Cell"    
  77.                               AlternationCount="2"    
  78.                               LoadingRow="GrdInfo_LoadingRow"    
  79.                               Background="{x:Null}"                           
  80.                               BorderBrush="{x:Null}"  >    
  81.                 </DataGrid>    
  82.     
  83. ...    
In the above code, I have created an export button control, browse button control, a checkbox to determine CSV file header, and a DataGrid control.
 
Step 3
 
Now, open the "Views\Pages\HomePage.xaml.cs" file and create the Import CSV file methods.
  1. ...  
  2.  
  3. #region Browse click event method.  
  4.   
  5.         /// <summary>  
  6.         /// Browse click event method.  
  7.         /// </summary>  
  8.         /// <param name="sender">Sender parameter</param>  
  9.         /// <param name="e">Event parameter</param>  
  10.         private void BtnBrowse_Click(object sender, RoutedEventArgs e)  
  11.         {  
  12.             try  
  13.             {  
  14.                 // Initialization.  
  15.                 OpenFileDialog browseDialog = new OpenFileDialog();  
  16.                 DataTable datatable = new DataTable();  
  17.   
  18.                 // Settings.  
  19.                 browseDialog.Filter = Strings.FILE_TYPES_FILTER_1;  
  20.   
  21.                 // Verification  
  22.                 if (browseDialog.ShowDialog() == true)  
  23.                 {  
  24.                     // Settings.  
  25.                     this.txtFilePath.Text = browseDialog.FileName;  
  26.   
  27.                     // Initialization.  
  28.                     string filePath = this.txtFilePath.Text;  
  29.                     bool isExist = this.chkHasHeader.IsChecked.Value;  
  30.   
  31.                     // Import CSV file.  
  32.                     datatable = CSVLibraryAK.Import(filePath, isExist);  
  33.   
  34.                     // Verification.  
  35.                     if (datatable.Rows.Count <= 0)  
  36.                     {  
  37.                         // Message.  
  38.                         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);  
  39.   
  40.                         // Info.  
  41.                         return;  
  42.                     }  
  43.   
  44.                     // Load Csv to datagrid.  
  45.                     this.grdLoad.ItemsSource = datatable.DefaultView;  
  46.   
  47.                     // Settings.  
  48.                     this.dataTableObj = datatable;  
  49.                 }  
  50.             }  
  51.             catch (Exception ex)  
  52.             {  
  53.                 // Info.  
  54.                 MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);  
  55.                 Console.Write(ex);  
  56.             }  
  57.         }  
  58.  
  59.         #endregion  
  60.   
  61. ... 
In the above code, I have created the "BtnBrowse_Click(...)" method, which will take the CSV file input from end-user and import the CSV file using CSVLibraryAK.Import(...) library method. Then, process the CSV file and load the resultant data from the CSV file into WPF DataGrid control.
 
Step 4
 
Now, open the "Views\Pages\HomePage.xaml.cs" file and create the Export CSV file methods.
  1. ...  
  2.  
  3. #region Export click event method.  
  4.   
  5.         /// <summary>  
  6.         /// Export click event method.  
  7.         /// </summary>  
  8.         /// <param name="sender">Sender parameter</param>  
  9.         /// <param name="e">Event parameter</param>  
  10.         private void Export_Click(object sender, RoutedEventArgs e)  
  11.         {  
  12.             try  
  13.             {  
  14.                 // Verification.  
  15.                 if (this.dataTableObj.Rows.Count <= 0)  
  16.                 {  
  17.                     // Message.  
  18.                     MessageBox.Show("There is no data available to export.""Warning", MessageBoxButton.OK, MessageBoxImage.Warning);  
  19.   
  20.                     // Info.  
  21.                     return;  
  22.                 }  
  23.   
  24.                 // Initialization.  
  25.                 SaveFileDialog exportDialog = new SaveFileDialog();  
  26.   
  27.                 // Settings.  
  28.                 exportDialog.Filter = Strings.FILE_TYPES_FILTER_1;  
  29.   
  30.                 // Verification.  
  31.                 if (exportDialog.ShowDialog() == true)  
  32.                 {  
  33.                     // Export to CSV file.  
  34.                     CSVLibraryAK.Export(exportDialog.FileName, this.dataTableObj);  
  35.   
  36.                     // Info.  
  37.                     MessageBox.Show("Data has been sucessfully exported to CSV file""Success", MessageBoxButton.OK, MessageBoxImage.Information);  
  38.                 }  
  39.             }  
  40.             catch (Exception ex)  
  41.             {  
  42.                 // Info.  
  43.                 MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);  
  44.                 Console.Write(ex);  
  45.             }  
  46.         }  
  47.  
  48.         #endregion  
  49.   
  50. ... 
In the above code, I have created an "Export_Click(...)" method which will export the DataGrid data into a CSV file using CSVLibraryAK.Export(...) library method. The end-user, then, stores the CSV file to their target location.
 
Step 5
 
Now, execute the project and you will be able to see the following in action.
 
 


 

Conclusion

 
In this article, you will learn to integrate CSVLibraryAK C#.NET library with WPF platform. You will also learn to import CSV files using CSVLibraryAK.Import(...) method. You will also learn to export the CSV file using CSVLibraryAK.Export(...) method at your target location on the desktop.