EPPlus 使用小结

简介

EPPlus是一个使用Open Office XML(xlsx)文件格式,能读写Excel 2007/2010 文件的开源组件,在导出Excel的时候不需要电脑上安装office,它的一个缺点就是不支持导出2003版的Excel(xls)。

.net core 通过nuget 包管理器添加
在这里插入图片描述

导入

这部分相对简单,直接看下代码:

using (ExcelPackage package = new ExcelPackage(existingFile))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
    
    //获取表格的列数和行数
    int rowCount = worksheet.Dimension.Rows;
    int colCount = worksheet.Dimension.Columns;
    for (int row = 1; row <= rowCount; row++)
    {
        // 具体的获取数据
        // worksheet.Cells[row, 1].Value.ToString();
    }
}

根据具体的业务情况,将excel中的数据导入到数据库中即可。

导出

简单导出

直接看代码:

// excelPath 为excel文件路径,如果没有,需要使用 FileStream 来创建,而不是使用 FileInfo
FileInfo existingFile = new FileInfo(excelPath);

using (ExcelPackage package = new ExcelPackage(existingFile))
{
    // sheetName 为 sheet 名称
    ExcelWorksheet worksheetIn = package.Workbook.Worksheets.Add(sheetName);
    // 第二参数为true 则会把 lstData定义的属性名称作为excel标题
    worksheetIn.Cells.LoadFromCollection(lstData, false);
    
    package.Save(); //Save the workbook.
}

样式格式化

还是直接看到代码:

Func<ExcelWorksheet, Color, bool> SetHeadStyle = (targetSheet, backgroundColor) =>
{
    var col = targetSheet.Dimension.Columns;
    // cells参数:第一个是开始行索引,第二个是开始列索引
    // 第三个是结束行索引,第四个是结束列的索引,注意:结束索引不能比开始索引小
    using (ExcelRange rng = targetSheet.Cells[1, 1, 1, col - 1])
    {
        // 对字体的设置
        rng.Style.Font.Bold = true;
        rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
        rng.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
        rng.Style.Font.Size = 8;
        rng.Style.Font.Color.SetColor(Color.FromArgb(0, 0, 128));
        
        // 单元格背景色的设置
        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
        rng.Style.Fill.BackgroundColor.SetColor(backgroundColor);

        //单独设置单元格底部边框样式和颜色(上下左右均可分开设置)
        rng.Style.Border.BorderAround(ExcelBorderStyle.Thin);

        rng.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
        rng.Style.Border.Right.Style = ExcelBorderStyle.Thin;

        // 自当使用文字大小
        rng.AutoFitColumns();
    }

    //单独设置单元格底部边框样式和颜色(上下左右均可分开设置)
    targetSheet.Cells[1, 3].Style.Border.Right.Style = ExcelBorderStyle.Thick;
    return true;
};
// 表示第一,二行,第一列就进行单元格合并
worksheetIn.Cells[1, 1, 2, 1].Merge = true;

使用方式:

SetHeadStyle(worksheetIn, Color.FromArgb(146, 208, 80));

也可参考此文https://www.jianshu.com/p/b7f588ccf26b

其他

EPPlus对现有excel的操作好像不是很好,即如果你对已经存在的sheet进行操作,然后保存的时候是报错的,但是添加和删除sheet都是没问题的。所以如果要对现有的sheet做操作可以先删除在添加即可。如下

var hasSheet = package.Workbook.Worksheets[sheetName];
if (hasSheet != null)
{
    package.Workbook.Worksheets.Delete(sheetName);
}
ExcelWorksheet worksheetIn = package.Workbook.Worksheets.Add(sheetName);

如果有对sheet位置有要求的,EPPlus默认添加sheet都是 Add 或者 Append 方法,没有插入到指定的位置的方法。但是经过查看源码,其提供了移动到指定为的方法,代码如下:

package.Workbook.Worksheets.MoveAfter(package.Workbook.Worksheets.Count - 1, 1); // 索引默认从1开始

源码定义如下:

 //
 // 摘要:
 //     Moves the source worksheet to the position after the target worksheet
 //
 // 参数:
 //   sourceName:
 //     The name of the source worksheet
 //
 //   targetName:
 //     The name of the target worksheet
 public void MoveAfter(string sourceName, string targetName);
 //
 // 摘要:
 //     Moves the source worksheet to the position after the target worksheet
 //
 // 参数:
 //   sourcePositionId:
 //     The id of the source worksheet
 //
 //   targetPositionId:
 //     The id of the target worksheet
 public void MoveAfter(int sourcePositionId, int targetPositionId);
 //
 // 摘要:
 //     Moves the source worksheet to the position before the target worksheet
 //
 // 参数:
 //   sourcePositionId:
 //     The id of the source worksheet
 //
 //   targetPositionId:
 //     The id of the target worksheet
 public void MoveBefore(int sourcePositionId, int targetPositionId);
 //
 // 摘要:
 //     Moves the source worksheet to the position before the target worksheet
 //
 // 参数:
 //   sourceName:
 //     The name of the source worksheet
 //
 //   targetName:
 //     The name of the target worksheet
 public void MoveBefore(string sourceName, string targetName);
 //
 // 摘要:
 //     Moves the source worksheet to the end of the worksheets collection
 //
 // 参数:
 //   sourceName:
 //     The name of the source worksheet
 public void MoveToEnd(string sourceName);
 //
 // 摘要:
 //     Moves the source worksheet to the end of the worksheets collection
 //
 // 参数:
 //   sourcePositionId:
 //     The position of the source worksheet
 public void MoveToEnd(int sourcePositionId);
 //
 // 摘要:
 //     Moves the source worksheet to the start of the worksheets collection
 //
 // 参数:
 //   sourceName:
 //     The name of the source worksheet
 public void MoveToStart(string sourceName);
 //
 // 摘要:
 //     Moves the source worksheet to the start of the worksheets collection
 //
 // 参数:
 //   sourcePositionId:
 //     The position of the source worksheet
 public void MoveToStart(int sourcePositionId);

总结

总体上来说,EPPlus操作相对还是毕竟简单的,而且从导出数据量上来看,也是很有优势的。有兴趣的可自行度娘了解其优劣情况。而如果想在.net core项目里面完成excel 的导入导出,也可考虑使用Magicodes.IE。这个是一个开源的项目,完全不用担心商用的问题,而且其内部实现也使用了EPPlus来实现的。

你可以通过以下步骤使用 EPPlus 将数据库数据导出到 Excel 中: 1. 连接数据库:使用 C# 中的 System.Data.SqlClient 命名空间和 SqlConnection 类连接数据库。 2. 执行 SQL 查询:使用 SqlCommand 类执行 SQL 查询,获取需要导出到 Excel 的数据。 3. 创建 Excel 文件:使用 EPPlus 创建一个新的 Excel 文件。 4. 添加工作表:使用 ExcelPackage.Workbook.Worksheets.Add() 方法添加一个新的工作表。 5. 添加表头:使用 ExcelWorksheet.Cells[row, column].Value 属性将表头添加到工作表中。 6. 将数据添加到工作表中:使用 ExcelWorksheet.Cells[row, column].Value 属性将数据添加到工作表中。 7. 保存 Excel 文件:使用 EPPlus 中的 Save() 方法将 Excel 文件保存到磁盘。 下面是示意代码: using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (ExcelPackage package = new ExcelPackage()) { ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1"); // Add headers worksheet.Cells[1, 1].Value = "Column 1"; worksheet.Cells[1, 2].Value = "Column 2"; worksheet.Cells[1, 3].Value = "Column 3"; // Add data int row = 2; while (reader.Read()) { worksheet.Cells[row, 1].Value = reader["Column1"]; worksheet.Cells[row, 2].Value = reader["Column2"]; worksheet.Cells[row, 3].Value = reader["Column3"]; row++; } // Save Excel file package.SaveAs(new FileInfo(@"C:\Temp\MyExcelFile.xlsx")); } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值