【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();
        }
    }
}
相关推荐
Excel工作圈4 小时前
凭证助手一键匹配已勾选抵扣发票与全量发票明细
数据库·excel
用户21991679703915 小时前
C# 14 中的新增功能
c#
qq_150841995 小时前
32位的CVI2010基于ExcelReport库无法正常访问64位EXCEL的解决方案
excel
weixin_431822405 小时前
办公自动化:通过字符串相似度算法找出Excel 中的重复数据
excel·零售
寄思~6 小时前
Excel 数据匹配工具 -笔记
笔记·python·学习·excel
垂葛酒肝汤6 小时前
放置挂机游戏的离线和在线收益unity实现
游戏·unity·c#
爱说实话8 小时前
C# 20260112
开发语言·c#
无风听海8 小时前
C#中实现类的值相等时需要保留null==null为true的语义
开发语言·c#