欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#?WPF實現(xiàn)數(shù)據(jù)記錄導(dǎo)出excel

 更新時間:2024年11月26日 09:21:36   作者:猿享天開  
這篇文章主要為大家詳細介紹了C#如何基于WPF實現(xiàn)數(shù)據(jù)記錄導(dǎo)出excel的功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

引言        

實現(xiàn)基于C#的WPF應(yīng)用程序?qū)С鰯?shù)據(jù)到 Excel 的功能,可以使用一個流行的庫,比如 EPPlus 或 ClosedXML。這些庫可以將 DataTable 數(shù)據(jù)導(dǎo)出為 Excel 文件,并提供簡單易用的 API。 下面是使用 EPPlus 庫實現(xiàn)導(dǎo)出功能的示例實現(xiàn)過程介紹。

為了更詳細說明實現(xiàn)過程,在 C# WPF 應(yīng)用程序中,我們可以創(chuàng)建一個學(xué)生成績查詢系統(tǒng),該系統(tǒng)從數(shù)據(jù)庫中提取數(shù)據(jù),在界面上顯示,并允許用戶將數(shù)據(jù)導(dǎo)出為 Excel 文件。我們將使用 DataGrid 顯示數(shù)據(jù),并使用 EPPlus 庫實現(xiàn)導(dǎo)出功能。以下是實現(xiàn)該功能的詳細步驟。

項目準備

步驟 1:設(shè)置數(shù)據(jù)庫

假設(shè)我們使用 SQLite 數(shù)據(jù)庫,其中有一個名為 StudentScores 的表。該表具有以下結(jié)構(gòu):

Column NameData Type
StudentIDINTEGER
NameTEXT
SubjectTEXT
ScoreREAL

步驟 2:安裝 NuGet 包

在項目中安裝以下 NuGet 包:

System.Data.SQLite:用于連接 SQLite 數(shù)據(jù)庫。(根據(jù)實際應(yīng)用中選擇數(shù)據(jù)庫,本文僅以 SQLite 數(shù)據(jù)庫為例)

EPPlus:用于導(dǎo)出數(shù)據(jù)到 Excel。

Install-Package System.Data.SQLite
Install-Package EPPlus

創(chuàng)建 WPF 界面

在 XAML 文件中,創(chuàng)建一個簡單的界面,包括一個 DataGrid 和一個導(dǎo)出按鈕。

<Window x:Class="StudentScoreApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="學(xué)生成績查詢" Height="400" Width="600">
    <Grid>
        <DataGrid x:Name="scoreDataGrid" AutoGenerateColumns="True" HeadersVisibility="Column" IsReadOnly="True" 
                  Margin="10,10,10,50" />
        <Button Content="導(dǎo)出" Width="100" Height="30" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="10" Click="ExportScore_Click"/>
    </Grid>
</Window>

后端代碼

步驟 1:從數(shù)據(jù)庫加載數(shù)據(jù)

在代碼后面,編寫從數(shù)據(jù)庫加載數(shù)據(jù)的方法。

using System;
using System.Data;
using System.Data.SQLite;
using System.Windows;
 
namespace StudentScoreApp
{
    public partial class MainWindow : Window
    {
        private DataTable _scoreTable;
 
        public MainWindow()
        {
            InitializeComponent();
            LoadData();
        }
 
        private void LoadData()
        {
            string connectionString = "Data Source=StudentScores.db;Version=3;";
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                string query = "SELECT StudentID, Name, Subject, Score FROM StudentScores";
                SQLiteDataAdapter adapter = new SQLiteDataAdapter(query, connection);
                _scoreTable = new DataTable();
                adapter.Fill(_scoreTable);
                scoreDataGrid.ItemsSource = _scoreTable.DefaultView;
            }
        }
    }
}

步驟 2:導(dǎo)出數(shù)據(jù)到 Excel

實現(xiàn) ExportScore_Click 方法,用于將數(shù)據(jù)導(dǎo)出到 Excel 文件。

using OfficeOpenXml;
using Microsoft.Win32;
using System.IO;
 
namespace StudentScoreApp
{
    public partial class MainWindow : Window
    {
        // 其他代碼...
 
        private void ExportScore_Click(object sender, RoutedEventArgs e)
        {
            if (_scoreTable == null || _scoreTable.Rows.Count == 0)
            {
                MessageBox.Show("沒有數(shù)據(jù)可導(dǎo)出。");
                return;
            }
 
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "Excel Files|*.xlsx",
                Title = "保存為 Excel 文件",
                FileName = "StudentScores.xlsx"
            };
 
            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    using (ExcelPackage package = new ExcelPackage())
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Scores");
 
                        // 將 DataTable 寫入 Excel
                        worksheet.Cells["A1"].LoadFromDataTable(_scoreTable, true);
 
                        // 保存到文件
                        FileInfo fileInfo = new FileInfo(saveFileDialog.FileName);
                        package.SaveAs(fileInfo);
 
                        MessageBox.Show("成績已成功導(dǎo)出到 Excel 文件。");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("導(dǎo)出時發(fā)生錯誤: " + ex.Message);
                }
            }
        }
    }
}

EPPlus  LicenseContext 屬性設(shè)置

由于EPPlus 5.0 及以上版本引入了一個商業(yè)許可模式,它需要在代碼中明確聲明使用的許可上下文。對于大多數(shù)非商業(yè)用途,可以將許可上下文設(shè)置LicenseContext.NonCommercial。這個非常重要,如果未設(shè)置將會在運行時報錯:

在ExcelPackage package = new ExcelPackage()報錯:Please set the ExcelPackage.LicenseContext property. See https://epplussoftware.com/developers/licenseexception

需要在代碼中設(shè)置 ExcelPackage.LicenseContext 屬性。這個非常重要,以下是解決上面問題的代碼示例:

// 在您的應(yīng)用程序入口點,如 Main 方法或者其他初始化代碼中執(zhí)行以下設(shè)置
ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // 設(shè)置為非商業(yè)使用

關(guān)鍵點說明

數(shù)據(jù)庫連接:使用 System.Data.SQLite 庫進行數(shù)據(jù)庫連接和數(shù)據(jù)檢索。確保連接字符串正確,并且數(shù)據(jù)庫文件可訪問。

數(shù)據(jù)綁定:將 DataTable 綁定到 DataGrid 的 ItemsSource,以便在界面上顯示數(shù)據(jù)。

EPPlus 導(dǎo)出:使用 EPPlus 庫將 DataTable 數(shù)據(jù)導(dǎo)出到 Excel。使用 LoadFromDataTable 方法可以輕松將表格加載到 Excel 工作表中。

用戶體驗:使用 SaveFileDialog 允許用戶選擇保存位置,并提供導(dǎo)出成功與否的反饋。

通過這些步驟,您可以在 WPF 應(yīng)用程序中實現(xiàn)從數(shù)據(jù)庫讀取、顯示學(xué)生成績,并能夠?qū)?shù)據(jù)導(dǎo)出到 Excel 文件的功能。這種方法不僅簡單而且高效,能夠處理大多數(shù)常見的需求。

到此這篇關(guān)于C# WPF實現(xiàn)數(shù)據(jù)記錄導(dǎo)出excel的文章就介紹到這了,更多相關(guān)WPF數(shù)據(jù)導(dǎo)出excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論