【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();
        }
    }
}
相关推荐
kylezhao20195 小时前
C# 文件的输入与输出(I/O)详解
java·算法·c#
kylezhao20196 小时前
C# TreeView 控件详解与应用
c#
FL16238631298 小时前
C# winform部署yolo26-obb旋转框检测的onnx模型演示源码+模型+说明
开发语言·c#
不坑老师13 小时前
小工具显出大才能——不坑盒子为教育数字化转型贡献“新方案”
microsoft·word·excel·ppt·office
骆驼爱记录14 小时前
Python程序打包全攻略
自动化·word·excel·wps·新人首发
hoiii18714 小时前
C# 俄罗斯方块游戏
开发语言·游戏·c#
chao18984415 小时前
C#实现OMRON FINS-TCP协议与PLC通信
网络·tcp/ip·c#
ytttr87315 小时前
基于C# WinForms实现多窗口通信
开发语言·microsoft·c#
GHL28427109016 小时前
用lingma合并俩个excel
ai·excel
小赖同学啊16 小时前
xmind用例通过excel整理方式(注意!!不是通过python解析ximind文件转化成用例)
开发语言·python·excel