【C#】C#读写Excel文件

【C#】C#读写Excel文件

码农世界 2024-06-12 后端 110 次浏览 0个评论

1.工具库选择

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

2.读文件测试

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.写文件测试

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();
        }
    }
}

转载请注明来自码农世界,本文标题:《【C#】C#读写Excel文件》

百度分享代码,如果开启HTTPS请参考李洋个人博客
每一天,每一秒,你所做的决定都会改变你的人生!

发表评论

快捷回复:

评论列表 (暂无评论,110人围观)参与讨论

还没有评论,来说两句吧...

Top