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();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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();
}
}
}