[Office software] C# calls NPOI to implement the loading and exporting functions of Excel files


1 Introduction

This article will introduce how to use C# and NPOI library to implement reading and writing operations of Excel files, and encapsulate them through buttons for loading files and exporting files. NPOI is a powerful .NET library that can easily handle Excel files. We will learn how to use NPOI to open an existing Excel file, read data, and write data to the Excel file.

2. Environment preparation

Before you begin, make sure you have the following environments installed:

  • Visual Studio (any version)
  • NPOI library

3. Sample code

The following is a sample code that demonstrates how to use C# and NPOI to implement read and write operations on Excel files, encapsulate them in functions, and add buttons for loading files and exporting files:

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. Results

After running the code, you will be able to select the Excel file to load via the Load File button and display the data from the file in the console. At the same time, you can also select the Excel file path to be exported through the export file button and write the data to the file.

5. Summary

This article introduces how to use C# and NPOI library to implement reading and writing operations of Excel files, and encapsulates them through buttons for loading files and exporting files. By using NPOI's API, we can easily process Excel files, read the data in them and write them. Hope this article helps you!

Guess you like

Origin blog.csdn.net/qq_38628970/article/details/134153111