Introduction
Implementing the functionality of exporting data to Excel for C#-based WPF applications, you can use a popular library such as EPPlus or ClosedXML. These libraries can export DataTable data into Excel files and provide an easy-to-use API. The following is an example implementation process for implementing the export function using the EPPlus library.
To illustrate the implementation process in more detail, in the C# WPF application, we can create a student grade query system that extracts data from the database, displays it on the interface, and allows the user to export the data as an Excel file. We will use DataGrid to display data and use the EPPlus library to implement export functionality. The following are detailed steps to implement this function.
Project preparation
Step 1: Set up the database
Suppose we use a SQLite database, which has a table called StudentScores. The table has the following structure:
Column Name | Data Type |
---|---|
StudentID | INTEGER |
Name | TEXT |
Subject | TEXT |
Score | REAL |
Step 2: Install the NuGet package
Install the following NuGet package in the project:
: Used to connect to SQLite database. (Based on the actual application, this article only takes the SQLite database as an example)
EPPlus: Used to export data to Excel.
Install-Package Install-Package EPPlus
Create a WPF interface
In the XAML file, create a simple interface that includes a DataGrid and an export button.
<Window x:Class="" xmlns="/winfx/2006/xaml/presentation" xmlns:x="/winfx/2006/xaml" Title="Student score inquiry" Height="400" Width="600"> <Grid> <DataGrid x:Name="scoreDataGrid" AutoGenerateColumns="True" HeadersVisibility="Column" IsReadOnly="True" Margin="10,10,10,50" /> <Button Content="Export" Width="100" Height="30" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="10" Click="ExportScore_Click"/> </Grid> </Window>
Backend code
Step 1: Load data from the database
After the code, write a method to load data from the database.
using System; using ; using ; using ; namespace StudentScoreApp { public partial class MainWindow : Window { private DataTable _scoreTable; public MainWindow() { InitializeComponent(); LoadData(); } private void LoadData() { string connectionString = "Data Source=;Version=3;"; using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { (); string query = "SELECT StudentID, Name, Subject, Score FROM StudentScores"; SQLiteDataAdapter adapter = new SQLiteDataAdapter(query, connection); _scoreTable = new DataTable(); (_scoreTable); = _scoreTable.DefaultView; } } } }
Step 2: Export the data to Excel
Implement the ExportScore_Click method to export data to an Excel file.
using OfficeOpenXml; using Microsoft.Win32; using ; namespace StudentScoreApp { public partial class MainWindow : Window { // Other codes... private void ExportScore_Click(object sender, RoutedEventArgs e) { if (_scoreTable == null || _scoreTable. == 0) { ("No data to export."); return; } SaveFileDialog saveFileDialog = new SaveFileDialog { Filter = "Excel Files|*.xlsx", Title = "Save as Excel file", FileName = "" }; if (() == true) { try { using (ExcelPackage package = new ExcelPackage()) { ExcelWorksheet worksheet = ("Scores"); // Write DataTable to Excel ["A1"].LoadFromDataTable(_scoreTable, true); // Save to file FileInfo fileInfo = new FileInfo(); (fileInfo); ("The results were successfully exported to the Excel file."); } } catch (Exception ex) { ("An error occurred while exporting: " + ); } } } } }
EPPlus LicenseContext property settings
Since EPPlus 5.0 and above introduces a commercial licensing model, it requires explicitly declaring the licensing context used in the code. For most non-commercial uses, the licensing context can be set. This is very important. If not set, an error will be reported at runtime:
Report an error in ExcelPackage package = new ExcelPackage(): Please set the property. See /developers/licenseexception
Properties need to be set in the code. This is very important, and the following is a code example to solve the above problem:
// Execute the following settings in your application entry point, such as the Main method or other initialization code = ; // Set for non-commercial use
Key points description
Database connection: Use the library to perform database connections and data retrieval. Make sure the connection string is correct and the database file is accessible.
Data binding: Bind the DataTable to the DataGrid's ItemsSource to display data on the interface.
EPPlus Export: Export DataTable data to Excel using the EPPlus library. Use the LoadFromDataTable method to load tables into Excel worksheets easily.
User Experience: Using SaveFileDialog allows users to select a save location and provide feedback on whether the export is successful or not.
These steps allow you to read from a database, display student grades, and export data to Excel files in a WPF application. This approach is not only simple but also efficient, and can handle most common needs.
This is the end of this article about C# WPF implementing data records export excel. For more related WPF data export excel content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!