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.
- Install CSVLibraryAK NuGet Package.
- Knowledge about Windows Presentation Form (WPF).
- Knowledge of C# Programming.
- 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.
- ...
-
- <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.
Step 3
Now, open the "Views\Pages\HomePage.xaml.cs" file and create the Import CSV file methods.
- ...
-
- #region Browse click event method.
-
-
-
-
-
-
- private void BtnBrowse_Click(object sender, RoutedEventArgs e)
- {
- try
- {
-
- OpenFileDialog browseDialog = new OpenFileDialog();
- DataTable datatable = new DataTable();
-
-
- browseDialog.Filter = Strings.FILE_TYPES_FILTER_1;
-
-
- if (browseDialog.ShowDialog() == true)
- {
-
- this.txtFilePath.Text = browseDialog.FileName;
-
-
- string filePath = this.txtFilePath.Text;
- bool isExist = this.chkHasHeader.IsChecked.Value;
-
-
- datatable = CSVLibraryAK.Import(filePath, isExist);
-
-
- if (datatable.Rows.Count <= 0)
- {
-
- 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.grdLoad.ItemsSource = datatable.DefaultView;
-
-
- this.dataTableObj = datatable;
- }
- }
- catch (Exception ex)
- {
-
- MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
- Console.Write(ex);
- }
- }
-
- #endregion
-
- ...
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.
- ...
-
- #region Export click event method.
-
-
-
-
-
-
- private void Export_Click(object sender, RoutedEventArgs e)
- {
- try
- {
-
- if (this.dataTableObj.Rows.Count <= 0)
- {
-
- MessageBox.Show("There is no data available to export.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
-
-
- return;
- }
-
-
- SaveFileDialog exportDialog = new SaveFileDialog();
-
-
- exportDialog.Filter = Strings.FILE_TYPES_FILTER_1;
-
-
- if (exportDialog.ShowDialog() == true)
- {
-
- CSVLibraryAK.Export(exportDialog.FileName, this.dataTableObj);
-
-
- MessageBox.Show("Data has been sucessfully exported to CSV file", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
- }
- }
- catch (Exception ex)
- {
-
- MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
- Console.Write(ex);
- }
- }
-
- #endregion
-
- ...
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.