Header Ads

WPF: Import/Export CSV File

In 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 32-bit machine. The code of the library is open sourced, so, anyone can compile the code to target bit machine or to make new changes.

Today, I shall be demonstrating 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.

Download Now!

Let's begin now.

1) Create a new MVC web project and name it "WPFImportExportCSV".  

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 i.e.

...

               <StackPanel Grid.Row="0"
                                Orientation="Horizontal"
                                VerticalAlignment="Center"
                                HorizontalAlignment="Center"
                                Margin="0,10,0,0">

                    <!-- Export button -->
                    <Button x:Name="export_to_csv" 
                            Click="Export_Click"
                            ToolTip="Export to CSV"
                            Margin="0,0,20,0">

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

                    <Border x:Name="txtFileBr"
                                            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="txtFilePath"
                                         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="btnBrowse"
                                Content="..." 
                                Foreground="Black"
                                Margin="5,0,0,0"
                                Height="30"
                                Width="50" 
                                Padding="0,0,0,0"
                                HorizontalAlignment="Left" 
                                VerticalAlignment="Center"
                                Click="BtnBrowse_Click" 
                                FontSize="18" 
                                FontWeight="Bold" />

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

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

...

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.

3) Now, Open "Views\Pages\HomePage.xaml.cs" file and create the import CSV file methods i.e.

...

#region Browse click event method.

        /// <summary>
        /// Browse click event method.
        /// </summary>
        /// <param name="sender">Sender parameter</param>
        /// <param name="e">Event parameter</param>
        private void BtnBrowse_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Initialization.
                OpenFileDialog browseDialog = new OpenFileDialog();
                DataTable datatable = new DataTable();

                // Settings.
                browseDialog.Filter = Strings.FILE_TYPES_FILTER_1;

                // Verification
                if (browseDialog.ShowDialog() == true)
                {
                    // Settings.
                    this.txtFilePath.Text = browseDialog.FileName;

                    // Initialization.
                    string filePath = this.txtFilePath.Text;
                    bool isExist = this.chkHasHeader.IsChecked.Value;

                    // Import CSV file.
                    datatable = CSVLibraryAK.Import(filePath, isExist);

                    // Verification.
                    if (datatable.Rows.Count <= 0)
                    {
                        // Message.
                        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);

                        // Info.
                        return;
                    }

                    // Load Csv to datagrid.
                    this.grdLoad.ItemsSource = datatable.DefaultView;

                    // Settings.
                    this.dataTableObj = datatable;
                }
            }
            catch (Exception ex)
            {
                // Info.
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Console.Write(ex);
            }
        }

        #endregion

...

In the above code, I have created "BtnBrowse_Click(...)" method, which will take 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.

4) Now, Open "Views\Pages\HomePage.xaml.cs" file and create the export CSV file methods i.e.

...

#region Export click event method.

        /// <summary>
        /// Export click event method.
        /// </summary>
        /// <param name="sender">Sender parameter</param>
        /// <param name="e">Event parameter</param>
        private void Export_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Verification.
                if (this.dataTableObj.Rows.Count <= 0)
                {
                    // Message.
                    MessageBox.Show("There is no data available to export.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);

                    // Info.
                    return;
                }

                // Initialization.
                SaveFileDialog exportDialog = new SaveFileDialog();

                // Settings.
                exportDialog.Filter = Strings.FILE_TYPES_FILTER_1;

                // Verification.
                if (exportDialog.ShowDialog() == true)
                {
                    // Export to CSV file.
                    CSVLibraryAK.Export(exportDialog.FileName, this.dataTableObj);

                    // Info.
                    MessageBox.Show("Data has been sucessfully exported to CSV file", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                // Info.
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Console.Write(ex);
            }
        }

        #endregion

...

In the above code, I have created "Export_Click(...)" method, which will export DataGrid data to a CSV file using CSVLibraryAK.Export(...) library method, end-user then store the CSV file to their target location.

5) Now, execute the project and you will be able to see the following in action i.e.



Conclusion

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

No comments