EPPlus常用代码
时间: 2024-04-24 20:23:31 浏览: 21
EPPlus 是一个用于操作 Excel 文件的开源库,可以进行读取、写入、修改和格式化 Excel 文件。以下是一些 EPPlus 的常用代码示例:
1. 创建新的 Excel 文件并写入数据:
```csharp
using OfficeOpenXml;
// 创建新的 Excel 文件
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage excelPackage = new ExcelPackage())
{
// 添加一个工作表
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
// 写入数据到单元格
worksheet.Cells["A1"].Value = "Hello";
worksheet.Cells["B1"].Value = "World";
// 保存文件
FileInfo fileInfo = new FileInfo("path/to/file.xlsx");
excelPackage.SaveAs(fileInfo);
}
```
2. 读取现有的 Excel 文件中的数据:
```csharp
using OfficeOpenXml;
// 打开现有的 Excel 文件
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage excelPackage = new ExcelPackage(new FileInfo("path/to/file.xlsx")))
{
// 获取第一个工作表
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[0];
// 读取单元格数据
string valueA1 = worksheet.Cells["A1"].Value.ToString();
string valueB1 = worksheet.Cells["B1"].Value.ToString();
// 输出数据
Console.WriteLine(valueA1);
Console.WriteLine(valueB1);
}
```
3. 修改现有的 Excel 文件中的数据:
```csharp
using OfficeOpenXml;
// 打开现有的 Excel 文件
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage excelPackage = new ExcelPackage(new FileInfo("path/to/file.xlsx")))
{
// 获取第一个工作表
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[0];
// 修改单元格数据
worksheet.Cells["A1"].Value = "New Value";
// 保存文件
FileInfo fileInfo = new FileInfo("path/to/file.xlsx");
excelPackage.SaveAs(fileInfo);
}
```
这些只是 EPPlus 的一些常用代码示例,EPPlus 还提供了更多的功能和方法,如合并单元格、设置样式、创建图表等。你可以根据具体需求去探索和应用更多的功能。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)