【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();
        }
    }
}
相关推荐
葡萄城技术团队1 天前
从100秒到10秒的性能优化,你真的掌握 Excel 的使用技巧了吗?
excel
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
QQ3596773452 天前
ArcGIS Pro实现基于 Excel 表格批量创建标准地理数据库(GDB)——高效数据库建库解决方案
数据库·arcgis·excel
唐青枫2 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务3 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther3 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
阿幸软件杂货间3 天前
Office转PDF转换器v1.0.py
开发语言·pdf·c#