Tạo các ứng dụng Windows Forms có thể mở tệp Excel khi nhấp vào nút là yêu cầu chung đối với các ứng dụng máy tính để bàn. Cho dù bạn đang xây dựng biểu mẫu nhập dữ liệu, trình tạo báo cáo hay công cụ xử lý tệp, việc tích hợp các thao tác Excel với các sự kiện nhấp vào nút là điều cần thiết.

Thao tác tệp Excel khi nhấp vào nút trong C# Windows Forms

Các tình huống thường gặp

  • 📁 Hộp thoại Mở tệp Excel: Cho phép người dùng chọn tệp Excel
  • 📊 Xử lý dữ liệu Excel: Đọc và hiển thị nội dung Excel
  • 💾 Xuất sang Excel: Tạo tệp Excel từ dữ liệu biểu mẫu
  • 🔄 Cập nhật tệp Excel: Sửa đổi các tệp Excel hiện có

Thiết lập Dự án Windows Forms

Đầu tiên, hãy tạo một dự án Windows Forms mới và thêm Openize.OpenXML SDK:

<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />
using Openize.Cells;
using System;
using System.IO;
using System.Windows.Forms;

Ví dụ 1: Mở tệp Excel khi nhấp vào nút

public partial class ExcelForm : Form
{
    private string selectedFilePath = "";
    
    public ExcelForm()
    {
        InitializeComponent();
    }
    
    // Button click to open file dialog
    private void btnOpenFile_Click(object sender, EventArgs e)
    {
        using (OpenFileDialog openFileDialog = new OpenFileDialog())
        {
            // Configure file dialog
            openFileDialog.Filter = "Excel Files|*.xlsx;*.xls|All Files|*.*";
            openFileDialog.Title = "Select Excel File";
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Documents);
            
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                selectedFilePath = openFileDialog.FileName;
                lblFileName.Text = $"Selected: {Path.GetFileName(selectedFilePath)}";
                btnProcessFile.Enabled = true;
                
                // Immediately show file info
                DisplayFileInfo();
            }
        }
    }
    
    private void DisplayFileInfo()
    {
        try
        {
            using (var workbook = new Workbook(selectedFilePath))
            {
                var worksheet = workbook.Worksheets[0];
                
                lblWorksheetName.Text = $"Worksheet: {worksheet.Name}";
                lblRowCount.Text = $"Rows: {worksheet.GetRowCount()}";
                lblColumnCount.Text = $"Columns: {worksheet.GetColumnCount()}";
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Error reading file info: {ex.Message}", "Error");
        }
    }
}

Ví dụ 2: Xử lý dữ liệu Excel và hiển thị trong DataGridView

public partial class ExcelProcessorForm : Form
{
    // Button click to process Excel file
    private void btnProcessExcel_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(selectedFilePath))
        {
            MessageBox.Show("Please select an Excel file first.", "No File Selected");
            return;
        }
        
        try
        {
            ProcessExcelFile(selectedFilePath);
            MessageBox.Show("Excel file processed successfully!", "Success");
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Error processing Excel file: {ex.Message}", "Error");
        }
    }
    
    private void ProcessExcelFile(string filePath)
    {
        using (var workbook = new Workbook(filePath))
        {
            var worksheet = workbook.Worksheets[0];
            
            // Clear existing data
            dataGridView1.Rows.Clear();
            dataGridView1.Columns.Clear();
            
            int rowCount = worksheet.GetRowCount();
            int colCount = worksheet.GetColumnCount();
            
            // Add columns to DataGridView
            for (int col = 1; col <= colCount; col++)
            {
                string headerText = worksheet.Cells[GetCellReference(1, col)].GetValue();
                if (string.IsNullOrEmpty(headerText))
                    headerText = $"Column {col}";
                    
                dataGridView1.Columns.Add($"Col{col}", headerText);
            }
            
            // Add rows to DataGridView
            for (int row = 2; row <= rowCount; row++)
            {
                string[] rowData = new string[colCount];
                for (int col = 1; col <= colCount; col++)
                {
                    string cellRef = GetCellReference(row, col);
                    rowData[col - 1] = worksheet.Cells[cellRef].GetValue();
                }
                dataGridView1.Rows.Add(rowData);
            }
            
            // Update status
            lblStatus.Text = $"Loaded {rowCount - 1} rows and {colCount} columns";
        }
    }
    
    static string GetCellReference(int row, int col)
    {
        return $"{GetColumnLetter(col)}{row}";
    }
    
    static string GetColumnLetter(int columnNumber)
    {
        string columnLetter = string.Empty;
        while (columnNumber > 0)
        {
            columnNumber--;
            columnLetter = (char)('A' + columnNumber % 26) + columnLetter;
            columnNumber /= 26;
        }
        return columnLetter;
    }
}

Ví dụ 3: Xuất dữ liệu biểu mẫu sang Excel khi nhấp vào nút

public partial class DataExportForm : Form
{
    // Button click to export data to Excel
    private void btnExportToExcel_Click(object sender, EventArgs e)
    {
        try
        {
            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter = "Excel Files|*.xlsx";
                saveFileDialog.Title = "Save Excel File";
                saveFileDialog.FileName = "ExportedData.xlsx";
                
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    ExportDataToExcel(saveFileDialog.FileName);
                    MessageBox.Show($"Data exported successfully to:\n{saveFileDialog.FileName}", "Export Complete");
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Error exporting data: {ex.Message}", "Export Error");
        }
    }
    
    private void ExportDataToExcel(string filePath)
    {
        using (var workbook = new Workbook())
        {
            var worksheet = workbook.Worksheets[0];
            worksheet.Name = "Exported Data";
            
            // Export form data
            worksheet.Cells["A1"].PutValue("Name");
            worksheet.Cells["B1"].PutValue("Email");
            worksheet.Cells["C1"].PutValue("Phone");
            worksheet.Cells["D1"].PutValue("Department");
            
            // Get data from form controls
            worksheet.Cells["A2"].PutValue(txtName.Text);
            worksheet.Cells["B2"].PutValue(txtEmail.Text);
            worksheet.Cells["C2"].PutValue(txtPhone.Text);
            worksheet.Cells["D2"].PutValue(cboDepartment.Text);
            
            // Export DataGridView data if available
            if (dataGridView1.Rows.Count > 0)
            {
                // Add headers from DataGridView
                for (int col = 0; col < dataGridView1.Columns.Count; col++)
                {
                    worksheet.Cells[GetCellReference(4, col + 1)].PutValue(dataGridView1.Columns[col].HeaderText);
                }
                
                // Add data rows
                for (int row = 0; row < dataGridView1.Rows.Count; row++)
                {
                    for (int col = 0; col < dataGridView1.Columns.Count; col++)
                    {
                        var cellValue = dataGridView1.Rows[row].Cells[col].Value?.ToString() ?? "";
                        worksheet.Cells[GetCellReference(row + 5, col + 1)].PutValue(cellValue);
                    }
                }
            }
            
            workbook.Save(filePath);
        }
    }
}

Ví dụ 4: Hoàn thành biểu mẫu Excel Manager

public partial class ExcelManagerForm : Form
{
    private string currentFilePath = "";
    
    public ExcelManagerForm()
    {
        InitializeComponent();
        UpdateButtonStates();
    }
    
    // Open Excel file
    private void btnOpen_Click(object sender, EventArgs e)
    {
        using (OpenFileDialog ofd = new OpenFileDialog())
        {
            ofd.Filter = "Excel Files|*.xlsx;*.xls";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                currentFilePath = ofd.FileName;
                LoadExcelFile();
                UpdateButtonStates();
            }
        }
    }
    
    // Create new Excel file
    private void btnNew_Click(object sender, EventArgs e)
    {
        try
        {
            using (var workbook = new Workbook())
            {
                var worksheet = workbook.Worksheets[0];
                worksheet.Name = "New Sheet";
                
                // Add some default content
                worksheet.Cells["A1"].PutValue("Column 1");
                worksheet.Cells["B1"].PutValue("Column 2");
                worksheet.Cells["C1"].PutValue("Column 3");
                
                using (SaveFileDialog sfd = new SaveFileDialog())
                {
                    sfd.Filter = "Excel Files|*.xlsx";
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        workbook.Save(sfd.FileName);
                        currentFilePath = sfd.FileName;
                        LoadExcelFile();
                        UpdateButtonStates();
                        MessageBox.Show("New Excel file created!", "Success");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Error creating file: {ex.Message}", "Error");
        }
    }
    
    // Save changes to Excel file
    private void btnSave_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(currentFilePath))
        {
            MessageBox.Show("No file is currently open.", "No File");
            return;
        }
        
        try
        {
            SaveDataGridToExcel();
            MessageBox.Show("File saved successfully!", "Saved");
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Error saving file: {ex.Message}", "Save Error");
        }
    }
    
    private void LoadExcelFile()
    {
        try
        {
            using (var workbook = new Workbook(currentFilePath))
            {
                var worksheet = workbook.Worksheets[0];
                
                // Load data into DataGridView
                dataGridView1.Rows.Clear();
                dataGridView1.Columns.Clear();
                
                int rowCount = worksheet.GetRowCount();
                int colCount = worksheet.GetColumnCount();
                
                // Add columns
                for (int col = 1; col <= colCount; col++)
                {
                    string header = worksheet.Cells[GetCellReference(1, col)].GetValue();
                    dataGridView1.Columns.Add($"Col{col}", string.IsNullOrEmpty(header) ? $"Column {col}" : header);
                }
                
                // Add rows
                for (int row = 2; row <= rowCount; row++)
                {
                    string[] rowData = new string[colCount];
                    for (int col = 1; col <= colCount; col++)
                    {
                        rowData[col - 1] = worksheet.Cells[GetCellReference(row, col)].GetValue();
                    }
                    dataGridView1.Rows.Add(rowData);
                }
                
                lblFileName.Text = Path.GetFileName(currentFilePath);
                lblStatus.Text = $"Loaded: {rowCount - 1} rows, {colCount} columns";
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Error loading file: {ex.Message}", "Load Error");
        }
    }
    
    private void SaveDataGridToExcel()
    {
        using (var workbook = new Workbook(currentFilePath))
        {
            var worksheet = workbook.Worksheets[0];
            
            // Save headers
            for (int col = 0; col < dataGridView1.Columns.Count; col++)
            {
                worksheet.Cells[GetCellReference(1, col + 1)].PutValue(dataGridView1.Columns[col].HeaderText);
            }
            
            // Save data
            for (int row = 0; row < dataGridView1.Rows.Count; row++)
            {
                for (int col = 0; col < dataGridView1.Columns.Count; col++)
                {
                    var value = dataGridView1.Rows[row].Cells[col].Value?.ToString() ?? "";
                    worksheet.Cells[GetCellReference(row + 2, col + 1)].PutValue(value);
                }
            }
            
            workbook.Save();
        }
    }
    
    private void UpdateButtonStates()
    {
        bool hasFile = !string.IsNullOrEmpty(currentFilePath);
        btnSave.Enabled = hasFile;
        btnProcess.Enabled = hasFile;
    }
}

Thực hành tốt nhất

  1. Luôn sử dụng Try-Catch: Xử lý các thao tác tệp một cách an toàn
  2. Xác thực đường dẫn tệp: Kiểm tra xem tệp có tồn tại trước khi xử lý không
  3. Phản hồi của người dùng: Hiển thị tiến trình cho các hoạt động dài
  4. Bật/Tắt nút: Cập nhật trạng thái UI dựa trên ngữ cảnh
  5. Bộ lọc tệp: Sử dụng bộ lọc thích hợp trong hộp thoại

Phần kết luận

Tích hợp các thao tác Excel với các nút bấm của Windows Forms cung cấp chức năng máy tính để bàn mạnh mẽ. Openize.OpenXML SDK giúp bạn dễ dàng:

  • ✅ Mở file Excel thông qua hộp thoại
  • ✅ Xử lý và hiển thị dữ liệu Excel
  • ✅ Xuất dữ liệu biểu mẫu sang Excel
  • ✅ Tạo giao diện quản lý Excel hoàn chỉnh Bắt đầu xây dựng các ứng dụng Windows Forms chuyên nghiệp hỗ trợ Excel ngay hôm nay!