EPPlus官方文档: https://www.epplussoftware.com/zh/Developers

Excel模板格式如下:
在这里插入图片描述

一、读取Excel中的数据到DataTable

// 需要引用的命名空间
using OfficeOpenXml;
using LicenseContext = OfficeOpenXml.LicenseContext;
using System.Data;

/// <summary>
/// 窗体中的全局变量,用于创建dt的列
/// </summary>
DataColumn dc = null;
/// <summary>
/// 窗体中的全局变量,用于存储从excel中读取的数据
/// </summary>
DataTable dt = new DataTable();

/// <summary>
/// 读取Excel中的数据到DataTable
/// </summary>
public void ReadExcelData(FileInfo fileInfo)
{
	// 读取注册码excel的数据
	dc = null;
	dt = new DataTable();
	using (var pck = new ExcelPackage(fileInfo)) // 打开注册码excel文件
	{
		ExcelWorksheet ws = pck.Workbook.Worksheets.Where(x => x.Name.ToLower() == "sheet1").FirstOrDefault();
		int minColumnNum = ws.Dimension.Start.Column;//工作区开始列
		int maxColumnNum = ws.Dimension.End.Column; //工作区结束列
		int minRowNum = ws.Dimension.Start.Row; //工作区开始行号
		int maxRowNum = ws.Dimension.End.Row; //工作区结束行号
		try
		{
			// Excel的工作区中有多少列就给DataTable添加多少列
			if (dc == null)
			{
				for (int j = 1; j <= maxColumnNum; j++)
				{
					vC = new DataColumn($"Column{j}", typeof(string));
					dt.Columns.Add(vC);
				}
			}
			// 将Excel中的数据放入DataTable,之所以从第3行开始循环,是因为前两行是表头,第3行开始才是数据
			for (int n = 3; n <= maxRowNum; n++)
			{
				DataRow vRow = dt.NewRow();
				for (int m = 1; m <= maxColumnNum; m++)
				{
					ws.Cells[n, 1].Value = n;
					if (ws.Cells[n, m].Value != null)
					{
						vRow[m - 1] = ws.Cells[n, m].Value;
				    }
				}
				dt.Rows.Add(vRow);
			}
			pck.Save();
		}
		catch (Exception ex)
		{
			MessageBoxEx.Show($"读取Excel文件数据时发生错误:{ex.ToString()}", "错误", MessageBoxButtonsEx.OK, MessageBoxIconEx.Error);
		}
	}
}

二、将数据保存到Excel

/// <summary>
/// 保存H1码按钮点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSaveParam_Click(object sender, EventArgs e)
{
	#region <测试数据>
	//txtNumber.Text = "F58672AN3020006";
	//byte[] h1CodeBytes = new byte[] { 0xD1,0x65,0x77,0x53,0x83,0x13,0x36,0x66,0x0F,0xF5,0x13,0xF7,0x1D,0x93,0x9E,
	//    0x0E,0xB0,0x8D,0xC3,0x5C,0xF2,0x8A,0xA0,0x70,0x86,0xFA,0x99,0x4F,0x43,0x7A,0x26,0xB4 };
	//txtH1Code.Text = ToHexString(h1CodeBytes);
	#endregion
	// 校验文本框是否为空
	if (string.IsNullOrEmpty(txtNumber.Text) || string.IsNullOrEmpty(txtH1Code.Text))
	{
		MessageBoxEx.Show($"序列号或H1码为空!无法保存!", "提示", MessageBoxButtonsEx.OK, MessageBoxIconEx.Information);
		return;
	}
	if (fileInfo == null)
	{
		MessageBoxEx.Show($"文件路径为空!无法保存!", "提示", MessageBoxButtonsEx.OK, MessageBoxIconEx.Information);
		return;
	}
	// 将读取的序列号和H1码保存到Excel文件
	if (dt.Rows.Count > 0) // Excel有数据的情况
	{
		DataRow[] drArr = dt.Select($"Column4 = '{txtNumber.Text}'");
		if (drArr.Length > 0)
		{
			var msg = $"Excel文件中已存在该序列号:{txtNumber.Text},无需重复保存!";
			AppendLog(LogType.None, msg); // 自定义函数,用于打印信息到richtextbox
			MessageBoxEx.Show(msg, "提示", MessageBoxButtonsEx.OK, MessageBoxIconEx.Information);
		}
		else
		{
			var rowsCount = dt.Rows.Count;
			DataRow dataRow = dt.NewRow();
			DataRow lastRow = dt.Rows[rowsCount - 2];
			int curr3ColValue = Convert.ToInt32(lastRow["Column3"].ToString()) + 1;
			dataRow["Column1"] = rowsCount + 2 + 1; // +2是因为表头占2行,所以新增加的倒数第二行数据应该+2+1
			dataRow["Column2"] = "";
			dataRow["Column3"] = curr3ColValue;
			dataRow["Column4"] = txtNumber.Text;
			dataRow["Column5"] = txtH1Code.Text;
			dt.Rows.Add(dataRow);
			dataRow = dt.NewRow();
			dataRow["Column1"] = rowsCount + 2 + 2; // +2是因为表头占2行,所以新增加的最后一行数据应该+2+2
			dataRow["Column2"] = "";
			dataRow["Column3"] = "对应生成注册码";
			dataRow["Column4"] = "";
			dataRow["Column5"] = "";
			dt.Rows.Add(dataRow);
			using (var pck = new ExcelPackage(fileInfo)) // 打开注册码excel文件
			{
				ExcelWorksheet ws = pck.Workbook.Worksheets.Where(x => x.Name.ToLower() == "sheet1").FirstOrDefault();
				ws.Cells["C1"].Value = $"美泰   申请日期:{DateTime.Now.ToString("yyyy年MM月dd日")}   设备:MNV403S  数量:{curr3ColValue}";
				ws.Cells["A3"].LoadFromDataTable(dt);
				pck.Save();
			}
			var msg = $"已成功保存序列号为:{txtNumber.Text},H1码为:{txtH1Code.Text}的数据!";
			AppendLog(LogType.None, msg);
			MessageBoxEx.Show(msg, "提示", MessageBoxButtonsEx.OK, MessageBoxIconEx.Information);
		}
	}
	else // Excel无数据的情况
	{
		DataRow dataRow = dt.NewRow();
		dataRow["Column1"] = 1; // +2是因为表头占2行,所以新增加的倒数第二行数据应该+2+1
		dataRow["Column2"] = "";
		dataRow["Column3"] = 1;
		dataRow["Column4"] = txtNumber.Text;
		dataRow["Column5"] = txtH1Code.Text;
		dt.Rows.Add(dataRow);
		dataRow = dt.NewRow();
		dataRow["Column1"] = 2; // +2是因为表头占2行,所以新增加的最后一行数据应该+2+2
		dataRow["Column2"] = "";
		dataRow["Column3"] = "对应生成注册码";
		dataRow["Column4"] = "";
		dataRow["Column5"] = "";
		dt.Rows.Add(dataRow);
		using (var pck = new ExcelPackage(fileInfo)) // 打开注册码excel文件
		{
			ExcelWorksheet ws = pck.Workbook.Worksheets.Where(x => x.Name.ToLower() == "sheet1").FirstOrDefault();
			ws.Cells["C1"].Value = $"美泰   申请日期:{DateTime.Now.ToString("yyyy年MM月dd日")}   设备:MNV403S  数量:{1}";
			ws.Cells["A3"].LoadFromDataTable(dt);
			pck.Save();
		}
		var msg = $"已成功保存序列号为:{txtNumber.Text},H1码为:{txtH1Code.Text}的数据!";
		AppendLog(LogType.None, msg);
		MessageBoxEx.Show(msg, "提示", MessageBoxButtonsEx.OK, MessageBoxIconEx.Information);
	}
}
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐