【C#】C#读写Excel文件

1.工具库选择

使用EPPlus读取Excel文件,在visual studio2022中安装最新NuGet。

2.读文件测试

csharp 复制代码
using OfficeOpenXml;
using OfficeOpenXml.Packaging.Ionic.Zip;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            
            // Excel文件路径
            string filePath = "D:\\Users\\.xlsx";

            // 打开Excel文件
            using (var package = new ExcelPackage(new FileInfo(filePath)))
            {
                // 获取第一个工作表
                var worksheet = package.Workbook.Worksheets[0];

                // 读取工作表内容
                for (int row = 1; row <= worksheet.Dimension.End.Row; row++)
                {
                    for (int col = 1; col <= worksheet.Dimension.End.Column; col++)
                    {
                        Console.Write(worksheet.Cells[row, col].Text + "\t");
                    }
                    Console.WriteLine();
                }
            }
            Console.ReadKey();
        }
    }
}

3.写文件测试

csharp 复制代码
using OfficeOpenXml;
using OfficeOpenXml.Packaging.Ionic.Zip;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using(var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add("sheet1");

                worksheet.Cells[1, 1].Value = "1";
                worksheet.Cells[1, 2].Value = "2";

                string filepath = "D:\\Users\\59723\\Desktop\\222.xlsx";
                FileInfo fileInfo = new FileInfo(filepath);
                package.SaveAs(fileInfo);
                Console.WriteLine("Excel file created successfully!");
            }          
            Console.ReadKey();
        }
    }
}
相关推荐
枯萎穿心攻击6 小时前
ECS由浅入深第三节:进阶?System 的行为与复杂交互模式
开发语言·unity·c#·游戏引擎
小码编匠6 小时前
WPF 自定义TextBox带水印控件,可设置圆角
后端·c#·.net
水果里面有苹果6 小时前
17-C#的socket通信TCP-1
开发语言·tcp/ip·c#
谁他个天昏地暗8 小时前
Java 实现 Excel 文件对比与数据填充
java·开发语言·excel
梦想blog8 小时前
Spring Boot + Easy Excel 自定义复杂样式导入导出
excel
阿蒙Amon14 小时前
C# Linq to SQL:数据库编程的解决方案
数据库·c#·linq
iCxhust16 小时前
c# U盘映像生成工具
开发语言·单片机·c#
emplace_back18 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
阿蒙Amon19 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#