C# programming, a method of using EPPlus to manipulate Excel files

1. The choice between EPPlus and NPOI

1. When importing and exporting data in desktop programs, Excel files will be manipulated. Commonly used third-party controls include NPOI and EPPlus .
2. Compared with NPOI, EPPlus's API is more friendly, and the ability to export data is more powerful than NPOI. However, NPOI is still stronger in the function of operating Excel ( comparison between C#
NPOI exporting Excel and EPPlus exporting Excel
): 20 columns, NPOI can export 40,000 data, and export 50,000 data when the memory overflows. EPPlus can export more than 200,000 data, and memory overflow when exporting 230,000 tests.

3. If you want to export more complex Excel, you can use NPOI, but EPPlus basically meets the general needs.

2. Basic introduction of EPPlus

EPPlus is an Open Office XML (xlsx) file format that can read and write Excel 2007/2010, and does not support Excel 2003.
The open source component of the file does not require office to be installed on the computer when exporting Excel. Official website address: http://epplus.codeplex.com/ If you
use it, you can directly obtain the corresponding dll from NuGet.

function points

Cell range, cell style, border, color, fill, font, number, alignment), chart, picture, shape, comment, table protection, encryption, pivot table, data verification, conditional format, VBA formula calculation

3. Reference URL

Introduction
Introduction Examples of
Commonly Used Attribute
Recommendations: EPlus Use Tutorial
Simple Attribute
Advanced Usage

4. Installation

nuget manager installation

Insert picture description here
Pay attention to the .net version requirements on the right
Insert picture description here

5. Attention

EPPlus official instructions point out that since the 5th edition, the open source agreement has changed. Commercial use requires a license, and personal development can be used directly through configuration.
If you use the latest version without configuration, an error will be reported.

Source code before version 5

Version 5 source code

License configuration method 1: Use the LicenseContext property in the ExcelPackage class

ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using(var package = new ExcelPackage(new FileInfo("MyWorkbook.xlsx")))
{
    
    
}

License configuration method 2: app.config

<appSettings>
    <!--The license context used-->
    <add key="EPPlus:ExcelPackage.LicenseContext" value="NonCommercial" />
</appSettings>

6, read the file

					//这里的文件选择对话框需要引用windows.forms程序集
 					OpenFileDialog ofd = new OpenFileDialog();
                    ofd.Filter = "Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx|所有文件|*.*";//文件类型
                    ofd.FilterIndex = 2;//默认选择上面类型中的第几个,从左到右,从1开始。
                    ofd.Title = "选择具体的文件";//对话框左上角标题
                    ofd.InitialDirectory = @"D:\";//默认打开的文件夹
                    ofd.Multiselect = false;//是否允许选中多个文件
                    ofd.ValidateNames = true;//验证用户输入是否是一个有效的Windows文件名。
                    ofd.CheckPathExists = true;//验证路径有效性。
                    ofd.CheckFileExists = true;//验证文件有效性。
                    ofd.ShowHelp = true;//出现一个帮助按钮,自定义帮助信息。
                    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
    
    
                        FilePath  = ofd.FileName;
					   //得到文件路径后,可以直接使用路径,也可以使用文件流的方式
		               //FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
		               //using (ExcelPackage package = new ExcelPackage(fs)
		                 
		                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
		                using (ExcelPackage package = new ExcelPackage(new FileInfo(FilePath)))
		                {
    
    
		                	//whichsheet指sheet表序号,从0开始
		                    ExcelWorksheet sheet = package.Workbook.Worksheets[whichsheet];
		                    var rownum = sheet.Dimension.Rows;//总行
		                    var colnum = sheet.Dimension.Rows;//总列
		                   
		                    //int minColumnNum = sheet.Dimension.Start.Column;//工作区开始列
		                    //int maxColumnNum = sheet.Dimension.End.Column; //工作区结束列
		                    //int minRowNum = sheet.Dimension.Start.Row; //工作区开始行号
		                    //int maxRowNum = sheet.Dimension.End.Row; //工作区结束行号
							
							//strlist是临时定义的一个存放获取的单元格数值的列表
		                    strlist.Clear();
		                    for (int i = 1; i <= rownum; i++)
		                    {
    
    
		                        var contstr = sheet.Cells[$"A{i}"].Value;//A是指A列,这里对A列所有的行进行读值
		                        if (contstr == null)//单元格没数值是空值
		                        {
    
    
		                            strlist.Add(new GridValue(""));
		                            continue;
		                        }
		                        strlist.Add(new GridValue(sheet.Cells[$"A{i}"].Value.ToString()));
		                    }
		                }
                    }
                    

7, write files

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            using (ExcelPackage package = new ExcelPackage(new FileInfo(FilePath)))
            {
    
    
                ExcelWorksheet sheet = package.Workbook.Worksheets[0];
                var rownum = sheet.Dimension.Rows;
                var colnum = sheet.Dimension.Columns;
                for (int i = 1; i <= rownum; i++)
                {
    
    
                    sheet.Cells[$"A{i}"].Value = "要写入的数值";
                }
                sheet.Cells[rownum, colnum].AutoFitColumns(0);//尝试自动调整列的宽度,如果有合并单元格,则不起作用
                package.Save();
            }
            System.Windows.MessageBox.Show("保存成功。");

8. Common attributes

1. File properties, Properties property can set some properties of Office

Insert picture description here

2. Sheet attributes

sheet.DefaultColWidth = 10; //默认列宽
sheet.DefaultRowHeight = 30; //默认行高
sheet.TabColor = Color.Blue; //Sheet Tab的颜色
sheet.Cells.Style.WrapText = true; //单元格文字自动换行
sheet.Cells.AutoFitColumns(0);//自动调整所有列的宽度
sheet.Cells[rownum, colnum].AutoFitColumns(0);//自动调整指定范围内所有列的宽度

3. Specify the style of the row or column (width, height, hidden, automatic line wrapping, number format, lock, etc.)

sheet.Column(1).Width = 10;
sheet.Row(1).Height = 30;
sheet.Column(1).Hidden = true;
sheet.Row(1).Hidden = true;
sheet.Column(1).Style.WrapText = true;
sheet.Column(1).Style.Numberformat.Format = "$#,###.00";
sheet.Row(1).Style.Locked = true;

4. ExcelRange class of cell range

//获取单元格范围的
public ExcelRange this[string Address] {
    
     get; }//Address是指"A1:C5"这种格式,如果没有字母,只是数字3:3表示整个第3行
public ExcelRange this[int Row, int Col] {
    
     get; }
public ExcelRange this[int FromRow, int FromCol, int ToRow, int ToCol] {
    
     get; }

//复制单元格:
public void Copy(ExcelRangeBase Destination);

//从二维数据集合中装载数据:
public ExcelRangeBase LoadFromCollection<T>(IEnumerable<T> Collection);
public ExcelRangeBase LoadFromDataReader(IDataReader Reader, bool PrintHeaders);
public ExcelRangeBase LoadFromText(FileInfo TextFile);
//这里的文件是指CSV文件
//数据装载时,会与ExcelRange的行列进行对应,将值设置到其中,这些单元格没有样式和数字格式

5, official

sheet.Cells[1, 3].range.Formula = "AVERAGE(A1, B1)";
sheet.Cells[1, 3].FormulaR1C1 = "AVERAGE(RC[-2], RC[-1])";
//以上两个公式表达意思相同——对于第一行,C列的值等于A列和B列的平均值

6. Cell

worksheet.Cells[1, 1].Value = "名称";//直接指定行列数进行赋值
worksheet.Cells["A1"].Value = "名称";//直接指定单元格进行赋值

Guess you like

Origin blog.csdn.net/qq_43307934/article/details/108549793