Using EPPlus to implement C# control Excel file content import and conversion
1. Add EPPlus
library
When using the EPPlus library, you need to make sure you add the correct references to your project. You can add references via:
-
Open your project.
-
In Solution Explorer, right-click References and select Manage NuGet Packages.
-
In the NuGet package manager, search for "EPPlus".
-
Install the EPPlus library.
Once you complete these steps, your project will contain the required EPPlus references and you should be able to use it in your code using OfficeOpenXml;
without encountering errors.
If you are still having issues, please make sure you have the EPPlus library installed in your development environment and that your project references the correct library version.
2. Sample operation
To parse the data in the Excel table into CurveEntity
entity classes, store the parsed data in curveEntities
a list, and then pass it to the control, you can use C# and some libraries to process Excel files.
In this example I will use EPPlus
the library to read an Excel file. First, make sure you've added EPPlus
the library to your project.
Next, create a method to parse the Excel table and store the data into curveEntities
a list. Here is a sample code:
// *****************************************************************************
// File: ExcelParser.cs
// Author: 李文国
// Email: [email protected]
// Date: 2023-09-25
// Project Name: WCSDynamics
// Version: 1.2.3
// Company: EVADA
// Mentor: 叶信文
// Copyright (C) 2023 EVADA. All rights reserved.
// *****************************************************************************
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using WCSDynamics.MinWCSDynamics.DataInput;
namespace WCSDynamics.MinWCSDynamics.Utility
{
public class ExcelParser
{
private List<CurveEntity> curveEntities = new List<CurveEntity>();
public List<CurveEntity> ParseExcel(string filePath)
{
FileInfo fileInfo = new FileInfo(filePath);
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;//EPPlus 5.0 以后的版本需要指定 商业证书 或者非商业证书。你需要在代码里指定证书或者降低EPPlus版本。在代码里面指定非商业证书
ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
if (worksheet == null)
{
throw new Exception("Excel文件为空或不包含任何工作表。");
}
int rowCount = worksheet.Dimension.Rows;
for (int row = 2; row <= rowCount; row++)
{
string name = worksheet.Cells[row, 1].Text; // 读取曲线名称
Color lineColor = ColorTranslator.FromHtml(worksheet.Cells[row, 2].Text); // 读取曲线颜色
List<PointF> dataSource = ParsePointData(worksheet.Cells[row, 3].Text); // 读取数据点
bool isVisible = bool.Parse(worksheet.Cells[row, 4].Text); // 读取是否可见
int pointCount = dataSource.Count; // 计算数据点个数
string description = worksheet.Cells[row, 5].Text; // 读取曲线介绍
CurveEntity curveEntity = new CurveEntity
{
Name = name,
LineColor = lineColor,
_dataSource = dataSource,
IsVisible = isVisible,
PointCount = pointCount,
Description = description
};
curveEntities.Add(curveEntity);
}
}
return curveEntities;
}
private List<PointF> ParsePointData(string pointData)
{
// 解析逗号分隔的坐标数据,例如:"1.0,2.0;3.0,4.0;5.0,6.0"
List<PointF> points = new List<PointF>();
string[] pointPairs = pointData.Split(';');
foreach (string pair in pointPairs)
{
string[] coordinates = pair.Split(',');
if (coordinates.Length == 2)
{
float x = float.Parse(coordinates[0]);
float y = float.Parse(coordinates[1]);
points.Add(new PointF(x, y));
}
}
return points;
}
}
}
The above code must be remembered:
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;//EPPlus 5.0 以后的版本需要指定 商业证书 或者非商业证书。你需要在代码里指定证书或者降低EPPlus版本。在代码里面指定非商业证书
To parse the data in the Excel table into CurveEntity
entity classes, store the parsed data in curveEntities
a list, and then pass it to the control, you can use C# and some libraries to process Excel files. In this example I will use EPPlus
the library to read an Excel file. First, make sure you've added EPPlus
the library to your project.
Next, create a method to parse the Excel table and store the data into curveEntities
a list. Here is a sample code:
csharpCopy codeusing OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
public class ExcelParser
{
private List<CurveEntity> curveEntities = new List<CurveEntity>();
public List<CurveEntity> ParseExcel(string filePath)
{
FileInfo fileInfo = new FileInfo(filePath);
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
if (worksheet == null)
{
throw new Exception("Excel file is empty or does not contain any worksheets.");
}
int rowCount = worksheet.Dimension.Rows;
for (int row = 2; row <= rowCount; row++)
{
string name = worksheet.Cells[row, 1].Text;
Color lineColor = ColorTranslator.FromHtml(worksheet.Cells[row, 2].Text);
List<PointF> dataSource = ParsePointData(worksheet.Cells[row, 3].Text);
bool isVisible = bool.Parse(worksheet.Cells[row, 4].Text);
int pointCount = dataSource.Count;
string description = worksheet.Cells[row, 5].Text;
CurveEntity curveEntity = new CurveEntity
{
Name = name,
LineColor = lineColor,
_dataSource = dataSource,
IsVisible = isVisible,
PointCount = pointCount,
Description = description
};
curveEntities.Add(curveEntity);
}
}
return curveEntities;
}
private List<PointF> ParsePointData(string pointData)
{
// 解析逗号分隔的坐标数据,例如:"1.0,2.0;3.0,4.0;5.0,6.0"
List<PointF> points = new List<PointF>();
string[] pointPairs = pointData.Split(';');
foreach (string pair in pointPairs)
{
string[] coordinates = pair.Split(',');
if (coordinates.Length == 2)
{
float x = float.Parse(coordinates[0]);
float y = float.Parse(coordinates[1]);
points.Add(new PointF(x, y));
}
}
return points;
}
}
Then, in your application, you can use the above class to parse the Excel file and pass the parsed data to the control. The sample code is as follows:
public class YourApplicationClass
{
private List<CurveEntity> curveEntities;
public void LoadExcelData(string filePath)
{
ExcelParser excelParser = new ExcelParser();
curveEntities = excelParser.ParseExcel(filePath);
// 将解析后的数据传递给控件
wcsDynamicsControl1.curveEntities = curveEntities;
}
}
Make sure to LoadExcelData
use the method call with the actual path to the Excel file to load and parse the data and pass it to the control.
ExcelParser
The following is a sample control test code that uses the previously designed class to parse Excel table data and pass it to the control:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
private List<CurveEntity> curveEntities = new List<CurveEntity>();
public Form1()
{
InitializeComponent();
// 解析Excel数据并将其存储到curveEntities集合中
ExcelParser excelParser = new ExcelParser();
curveEntities = excelParser.ParseExcel("your_excel_file_path.xlsx");
// 将解析后的数据传递给控件
wcsDynamicsControl1.curveEntities = this.curveEntities;
}
}
}
Please your_excel_file_path.xlsx
replace it with your actual Excel file path. This code uses a class in the constructor ExcelParser
to parse the Excel file and pass the parsed data to the control. Make sure your project has included ExcelParser
the class definition and correctly referenced the EPPlus library.
3.Excel file example
To create an .xlsx file to parse the data using the previously provided ExcelParser
classes, you can use an Excel editor (such as Microsoft Excel) to create the file and ensure the following format:
- Create an Excel worksheet with the following columns:
- Column 1: Curve name
- Column 2: Curve color (expressed using HTML colors, such as "#FF0000" for red)
- Column 3: Data point coordinates (comma-separated pairs of coordinates, with semicolons separating different data points, e.g. "1.0,2.0;3.0,4.0;5.0,6.0")
- Column 4: Whether it is visible (indicated by "true" or "false")
- Column 5: Curve introduction
- Fill in the rows of the worksheet with data. Here is an example:
Curve name | Curve color | data point coordinates | visible or not | Curve introduction |
---|---|---|---|---|
SPU1 | #FF0000 | 1.0,2.0;2.0,4.0;3.0,6.0 | true | Curve 1 |
Monitor 2 | #0000FF | 1.0,3.0;2.0,5.0;3.0,7.0 | true | Curve 2 |
Electricity 3 | #FFFF00 | 1.0,4.0;2.0,6.0;3.0,8.0 | true | Curve 3 |