【办公软件】C#调用NPOI实现Excel文件的加载、导出功能


1. 引言

本文将介绍如何使用C#和NPOI库实现Excel文件的读写操作,并通过加载文件和导出文件的按钮进行封装。NPOI是一个强大的.NET库,可以轻松处理Excel文件。我们将学习如何使用NPOI打开现有的Excel文件、读取数据,并将数据写入到Excel文件中。

2. 环境准备

在开始之前,请确保已安装以下环境:

  • Visual Studio(任何版本)
  • NPOI库

3. 示例代码

下面是一个示例代码,演示了如何使用C#和NPOI实现Excel文件的读写操作,并封装在函数中,同时添加加载文件和导出文件的按钮:

using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        Application.Run(new Form1());
    }
}

public class Form1 : Form
{
    
    
    private Button loadButton;
    private Button exportButton;
    private DataTable dataTable;

    public Form1()
    {
    
    
        loadButton = new Button();
        loadButton.Text = "加载文件";
        loadButton.Click += LoadButton_Click;

        exportButton = new Button();
        exportButton.Text = "导出文件";
        exportButton.Click += ExportButton_Click;

        Controls.Add(loadButton);
        Controls.Add(exportButton);
    }

    private void LoadButton_Click(object sender, EventArgs e)
    {
    
    
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx";
        openFileDialog.Title = "选择要加载的Excel文件";

        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
    
    
            string filePath = openFileDialog.FileName;
            dataTable = LoadExcelFile(filePath);
        }
    }

    private void ExportButton_Click(object sender, EventArgs e)
    {
    
    
        if (dataTable == null)
        {
    
    
            MessageBox.Show("请先加载Excel文件!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }

        SaveFileDialog saveFileDialog = new SaveFileDialog();
        saveFileDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx";
        saveFileDialog.Title = "选择要导出的Excel文件路径";

        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
    
    
            string filePath = saveFileDialog.FileName;
            ExportExcelFile(filePath, dataTable);
        }
    }

    private DataTable LoadExcelFile(string filePath)
    {
    
    
        DataTable dataTable = new DataTable();
        FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        ISheet sheet = workbook.GetSheetAt(0);

        // 读取表头
        IRow headerRow = sheet.GetRow(0);
        for (int i = 0; i < headerRow.LastCellNum; i++)
        {
    
    
            dataTable.Columns.Add(headerRow.GetCell(i).ToString());
        }

        // 读取数据
        for (int row = 1; row <= sheet.LastRowNum; row++)
        {
    
    
            IRow currentRow = sheet.GetRow(row);
            DataRow dataRow = dataTable.NewRow();
            for (int col = 0; col < currentRow.LastCellNum; col++)
            {
    
    
                dataRow[col] = currentRow.GetCell(col)?.ToString();
            }
            dataTable.Rows.Add(dataRow);
        }

        file.Close();
        Console.WriteLine("加载文件完成!");
        return dataTable;
    }

    private void ExportExcelFile(string filePath, DataTable dataTable)
    {
    
    
        XSSFWorkbook workbook = new XSSFWorkbook();
        ISheet sheet = workbook.CreateSheet("Sheet1");

        // 写入表头
        IRow headerRow = sheet.CreateRow(0);
        for (int i = 0; i < dataTable.Columns.Count; i++)
        {
    
    
            headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
        }

        // 写入数据
        for (int row = 0; row < dataTable.Rows.Count; row++)
        {
    
    
            IRow newRow = sheet.CreateRow(row + 1);
            for (int col = 0; col < dataTable.Columns.Count; col++)
            {
    
    
                newRow.CreateCell(col).SetCellValue(dataTable.Rows[row][col]?.ToString());
            }
        }

        FileStream writeFile = new FileStream(filePath, FileMode.Create, FileAccess.Write);
        workbook.Write(writeFile);
        writeFile.Close();

        Console.WriteLine("导出文件完成!");
    }
}

4. 结果

运行代码后,将能够通过加载文件按钮选择要加载的Excel文件,并在控制台中显示文件中的数据。同时,还可以通过导出文件按钮选择要导出的Excel文件路径,并将数据写入到文件中。

5. 总结

本文介绍了如何使用C#和NPOI库实现Excel文件的读写操作,并通过加载文件和导出文件的按钮进行封装。通过使用NPOI的API,我们可以轻松地处理Excel文件,读取其中的数据并进行写入。希望本文对你有所帮助!

猜你喜欢

转载自blog.csdn.net/qq_38628970/article/details/134153111