C# Excel导入、导出
public void ImportExcel(HttpContext context)
{
StringBuilder errorMsg = new StringBuilder(); // 错误信息
try
{
#region 1.获取Excel文件并转换为一个List集合
// 1.1存放Excel文件到本地服务器
HttpPostedFile filePost = context.Request.Files["filed"]; // 获取上传的文件
string filePath = ExcelHelper.SaveExcelFile(filePost); // 保存文件并获取文件路径
// 单元格抬头
// key:实体对象属性名称,可通过反射获取值
// value:属性对应的中文注解
Dictionary<string, string> cellheader = new Dictionary<string, string> {
{ "Name", "姓名" },
{ "Age", "年龄" },
{ "GenderName", "性别" },
{ "TranscriptsEn.ChineseScores", "语文成绩" },
{ "TranscriptsEn.MathScores", "数学成绩" },
};
// 1.2解析文件,存放到一个List集合里
List<UserEntity> enlist = ExcelHelper.ExcelToEntityList<UserEntity>(cellheader, filePath, out errorMsg);
#endregion
#region 2.对List集合进行有效性校验
#region 2.1检测必填项是否必填
for (int i = 0; i < enlist.Count; i++)
{
UserEntity en = enlist[i];
string errorMsgStr = "第" + (i + 1) + "行数据检测异常:";
bool isHaveNoInputValue = false; // 是否含有未输入项
if (string.IsNullOrEmpty(en.Name))
{
errorMsgStr += "姓名列不能为空;";
isHaveNoInputValue = true;
}
if (isHaveNoInputValue) // 若必填项有值未填
{
en.IsExcelVaildateOK = false;
errorMsg.AppendLine(errorMsgStr);
}
}
#endregion
#region 2.2检测Excel中是否有重复对象
for (int i = 0; i < enlist.Count; i++)
{
UserEntity enA = enlist[i];
if (enA.IsExcelVaildateOK == false) // 上面验证不通过,不进行此步验证
{
continue;
}
for (int j = i + 1; j < enlist.Count; j++)
{
UserEntity enB = enlist[j];
// 判断必填列是否全部重复
if (enA.Name == enB.Name)
{
enA.IsExcelVaildateOK = false;
enB.IsExcelVaildateOK = false;
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/68715.html