ExamScoreImportService.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. using Furion.ClayObject.Extensions;
  2. using Furion.DatabaseAccessor.Extensions;
  3. using NPOI.OpenXmlFormats.Spreadsheet;
  4. using NPOI.SS.UserModel;
  5. using NPOI.XSSF.UserModel;
  6. using System;
  7. using System.IO.Compression;
  8. using YBEE.EQM.Core;
  9. namespace YBEE.EQM.Application;
  10. /// <summary>
  11. /// 学生成绩导入服务
  12. /// </summary>
  13. public class ExamScoreImportService : IExamScoreImportService, ITransient
  14. {
  15. private readonly IRepository<ExamScore> _rep;
  16. private readonly ISchoolClassService _schoolClassService;
  17. private readonly IExamGradeService _examGradeService;
  18. private readonly IExportExcelService _exportExcelService;
  19. public ExamScoreImportService(IRepository<ExamScore> rep, ISchoolClassService schoolClassService, IExamGradeService examGradeService, IExportExcelService exportExcelService)
  20. {
  21. _rep = rep;
  22. _schoolClassService = schoolClassService;
  23. _examGradeService = examGradeService;
  24. _exportExcelService = exportExcelService;
  25. }
  26. /// <summary>
  27. /// 批量导入前期未上报学生名单的各科成绩(初始化)
  28. /// </summary>
  29. /// <param name="filePath"></param>
  30. /// <param name="examPlanId"></param>
  31. /// <returns></returns>
  32. public async Task UploadImportWithoutStudentTotalScore(string filePath, int examPlanId)
  33. {
  34. /* ----------------------------------------------------------
  35. * 处理步骤:
  36. * 1.验证表头
  37. * 2.读取数据
  38. * 3.处理班级
  39. * 4.处理学生
  40. * 5.批量插入
  41. ---------------------------------------------------------- */
  42. try
  43. {
  44. #region 1.验证表结构
  45. using FileStream fs = new(filePath, FileMode.Open, FileAccess.Read);
  46. IWorkbook workbook = ExcelUtil.GetWorkbook(filePath, fs);
  47. var sheet = workbook.GetSheetAt(0);
  48. var rows = sheet.GetRowEnumerator();
  49. // 少于2行验证
  50. if (sheet.LastRowNum < 2)
  51. {
  52. //"第一行应为填写说明,第二行应为标题行,请勿修改模板结构。"
  53. return;
  54. }
  55. // 读取表头
  56. rows.MoveNext();
  57. IRow headerRow = (IRow)rows.Current;
  58. int index = 0;
  59. int SAMPLE_TYPE_INDEX = index++;
  60. int SCHOOL_ID_INDEX = index++;
  61. int SCHOOL_NAME_INDEX = index++;
  62. int SCHOOL_BID_INDEX = index++;
  63. int SCHOOL_BNAME_INDEX = index++;
  64. int NAME_INDEX = index++;
  65. int CERT_TYPE_INDEX = index++;
  66. int ID_NUM_INDEX = index++;
  67. int EXAM_NUMBER_INDEX = index++;
  68. int COURSE_COMB_INDEX = index++;
  69. int GRADE_INDEX = index++;
  70. int CLASS_INDEX = index++;
  71. int COURSE_START_INDEX = index;
  72. Dictionary<int, string> headers = new()
  73. {
  74. { SAMPLE_TYPE_INDEX, "抽样类型" },
  75. { SCHOOL_ID_INDEX, "学校ID" },
  76. { SCHOOL_NAME_INDEX, "学校" },
  77. { SCHOOL_BID_INDEX, "校区ID" },
  78. { SCHOOL_BNAME_INDEX, "校区" },
  79. { NAME_INDEX, "姓名" },
  80. { CERT_TYPE_INDEX, "证件类型" },
  81. { ID_NUM_INDEX, "证件号码" },
  82. { EXAM_NUMBER_INDEX, "考号" },
  83. { COURSE_COMB_INDEX, "选科组合" },
  84. { GRADE_INDEX, "年级" },
  85. { CLASS_INDEX, "班级" },
  86. };
  87. List<string> headerErrors = new();
  88. for (int i = 0; i < COURSE_START_INDEX; i++)
  89. {
  90. if (headerRow.GetCell(i)?.ToString() != headers[i])
  91. {
  92. char letter = (char)('A' + i);
  93. headerErrors.Add(letter.ToString());
  94. }
  95. }
  96. if (headerErrors.Any())
  97. {
  98. string columnErrors = string.Join("、", headerErrors);
  99. //result.ErrorMessage.Add($"第1行标题行{columnErrors}列名错误。从A列开始依次应为抽样类型、学校ID、学校、姓名、证件类型、证件号码、考号、年级、班级。");
  100. //return result;
  101. return;
  102. }
  103. //result.StructureCorrect = true;
  104. #endregion
  105. #region 2.读取数据
  106. var examPlan = await _rep.Change<ExamPlan>().DetachedEntities.FirstOrDefaultAsync(t => t.Id == examPlanId) ?? throw Oops.Oh(ErrorCode.E2001, "监测计划");
  107. var examGradeDict = (await _examGradeService.GetListByExamPlanId(examPlanId)).ToDictionary(t => t.Grade.GradeNumber);
  108. var courseDict = (await _rep.Change<Course>().DetachedEntities.ToListAsync()).ToDictionary(t => t.Name);
  109. // 获取需要导入的科目列表
  110. Dictionary<int, Course> courses = new();
  111. for (int gi = COURSE_START_INDEX; gi < headerRow.LastCellNum; gi++)
  112. {
  113. var cn = headerRow.GetCell(gi).ToString() ?? "";
  114. if (string.IsNullOrEmpty(cn))
  115. {
  116. continue;
  117. }
  118. courses.Add(gi, courseDict[cn]);
  119. }
  120. int rn = 1;
  121. List<ExamScoreImportDto> sourceItems = new();
  122. while (rows.MoveNext())
  123. {
  124. rn++;
  125. IRow row = (IRow)rows.Current;
  126. string rv = row.GetCell(0)?.ToString().Trim() ?? "";
  127. if (rv == "")
  128. {
  129. break;
  130. }
  131. for (int gi = COURSE_START_INDEX; gi < headerRow.LastCellNum; gi++)
  132. {
  133. var course = courses[gi];
  134. var sbid = row.GetCell(SCHOOL_BID_INDEX)?.NumericCellValue;
  135. var ccid = row.GetCell(COURSE_COMB_INDEX)?.NumericCellValue;
  136. ExamScoreImportDto item = new()
  137. {
  138. RowNumber = rn,
  139. SampleType = (ExamSampleType)row.GetCell(SAMPLE_TYPE_INDEX).NumericCellValue,
  140. SysOrgId = (short)row.GetCell(SCHOOL_ID_INDEX).NumericCellValue,
  141. SysOrgBranchId = sbid > 0 ? (short)sbid : null,
  142. StudentName = StringUtil.ClearWhite(row.GetCell(NAME_INDEX)?.ToString() ?? ""),
  143. CertificateType = (CertificateType)row.GetCell(CERT_TYPE_INDEX).NumericCellValue,
  144. IdNumber = StringUtil.ClearIdNumber(row.GetCell(ID_NUM_INDEX)?.ToString() ?? ""),
  145. ExamNumber = row.GetCell(EXAM_NUMBER_INDEX)?.ToString() ?? "",
  146. GradeNumber = (short)row.GetCell(GRADE_INDEX).NumericCellValue,
  147. ClassNumber = (short)row.GetCell(CLASS_INDEX).NumericCellValue,
  148. CourseId = course.Id,
  149. NceeCourseCombId = ccid > 0 ? (short)ccid : null,
  150. };
  151. string scoreStr = row.GetCell(gi)?.ToString() ?? "";
  152. if (decimal.TryParse(scoreStr, out decimal score))
  153. {
  154. item.Score = score;
  155. }
  156. else if (scoreStr.Contains('特') || scoreStr.Contains('缺'))
  157. {
  158. item.IsExcluded = true;
  159. }
  160. if (item.IdNumber.Length == 18)
  161. {
  162. if (int.TryParse(item.IdNumber.AsSpan(16, 1), out int gn))
  163. {
  164. item.Gender = (short)(gn % 2 == 0 ? 2 : 1);
  165. }
  166. }
  167. var eg = examGradeDict[item.GradeNumber];
  168. item.ExamGradeId = eg.Id;
  169. item.GradeId = eg.GradeId;
  170. item.GradeBeginYear = eg.GradeBeginYear;
  171. item.GradeEndYear = eg.GradeEndYear;
  172. item.SchoolClassId = _schoolClassService.GetSchoolClassId(examPlan.EducationStage, item.SysOrgId, eg.GradeBeginYear, item.ClassNumber);
  173. sourceItems.Add(item);
  174. }
  175. }
  176. workbook.Close();
  177. fs.Close();
  178. #endregion
  179. #region 3.处理班级
  180. var scs = sourceItems.GroupBy(t => t.SchoolClassId).Select(t => new BatchInsertSchoolClassInput
  181. {
  182. Id = t.Key,
  183. SysOrgId = t.FirstOrDefault().SysOrgId,
  184. SysOrgBranchId = t.FirstOrDefault().SysOrgBranchId,
  185. EducationStage = examPlan.EducationStage,
  186. EducationYears = examPlan.EducationYears,
  187. ClassNumber = t.FirstOrDefault().ClassNumber,
  188. GradeBeginYear = t.FirstOrDefault().GradeBeginYear,
  189. GradeEndYear = t.FirstOrDefault().GradeEndYear,
  190. }).Distinct().ToList();
  191. // 插入没有的班级
  192. await _schoolClassService.BatchInsert(scs);
  193. #endregion
  194. #region 4.处理学生
  195. // 清理学生
  196. string deleteStudentSql = $"DELETE FROM exam_student WHERE exam_plan_id = {examPlanId};";
  197. await _rep.SqlNonQueryAsync(deleteStudentSql);
  198. var uid = CurrentSysUserInfo.SysUserId;
  199. if (uid == 0)
  200. {
  201. uid = 1;
  202. }
  203. var stus = sourceItems.GroupBy(t => t.RowNumber).Select(t => t.FirstOrDefault()).ToList();
  204. List<string> insertValues = new();
  205. int scount = stus.Count;
  206. for (int i = 0; i < scount; i++)
  207. {
  208. var t = stus[i];
  209. string sobid = "NULL";
  210. if (t.SysOrgBranchId.HasValue)
  211. {
  212. sobid = t.SysOrgBranchId.ToString();
  213. }
  214. insertValues.Add($"({examPlanId}, {t.SysOrgId}, {sobid}, {t.ExamGradeId}, {t.GradeId}, {t.SchoolClassId}, {t.ClassNumber}, '{t.ExamNumber}', '{t.StudentName}', {(short)t.CertificateType}, '{t.IdNumber}', {t.Gender}, {uid}, CURRENT_TIMESTAMP, 0)");
  215. if ((i + 1) % 1000 == 0 || i == scount - 1)
  216. {
  217. string insertSql = $@"
  218. INSERT INTO exam_student(exam_plan_id, sys_org_id, sys_org_branch_id, exam_grade_id, grade_id, school_class_id, class_number, exam_number, `name`, certificate_type, id_number, gender, create_sys_user_id, create_time, is_deleted) VALUES
  219. {string.Join(",", insertValues)}
  220. ";
  221. await _rep.SqlNonQueryAsync(insertSql);
  222. insertValues.Clear();
  223. }
  224. }
  225. #endregion
  226. #region 5.批量导入
  227. // 清理成绩
  228. string deleteScoreSql = $"DELETE FROM exam_score WHERE exam_plan_id = {examPlanId};";
  229. await _rep.SqlNonQueryAsync(deleteScoreSql);
  230. List<string> selects = new();
  231. scount = sourceItems.Count;
  232. for (int i = 0; i < scount; i++)
  233. {
  234. var t = sourceItems[i];
  235. string sobid = "NULL";
  236. if (t.SysOrgBranchId.HasValue)
  237. {
  238. sobid = t.SysOrgBranchId.ToString();
  239. }
  240. string ccid = "NULL";
  241. if (t.NceeCourseCombId.HasValue)
  242. {
  243. ccid = t.NceeCourseCombId.ToString();
  244. }
  245. var ied = t.IsExcluded ? 1 : 0;
  246. selects.Add($@"
  247. SELECT {(short)t.SampleType} est, {t.SysOrgId} soid, {sobid} as sobid, {t.GradeId} gid, {examPlan.SemesterId} smid, {t.SchoolClassId} scid, {t.ClassNumber} cn, '{t.ExamNumber}' en, {ccid} ccid, {t.CourseId} cid, {t.Score} s, {ied} ied ");
  248. if ((i + 1) % 500 == 0 || i == scount - 1)
  249. {
  250. string insertSql = $@"
  251. INSERT INTO exam_score(exam_plan_id, education_stage, exam_sample_type, sys_org_id, sys_org_branch_id, grade_id, semester_id, school_class_id, class_number, exam_student_id, ncee_course_comb_id, course_id, score, is_excluded)
  252. SELECT {examPlanId}, {(short)examPlan.EducationStage}, T1.est, T1.soid, T1.sobid, T1.gid, T1.smid, T1.scid, T1.cn, T2.id, T1.ccid, T1.cid, T1.s, T1.ied
  253. FROM
  254. ({string.Join("UNION ALL", selects)}
  255. ) AS T1
  256. JOIN (SELECT id, school_class_id, exam_number FROM exam_student WHERE exam_plan_id = {examPlanId}) AS T2
  257. ON T1.scid = T2.school_class_id AND T1.en = T2.exam_number
  258. ";
  259. await _rep.SqlNonQueryAsync(insertSql);
  260. selects.Clear();
  261. }
  262. }
  263. #endregion
  264. }
  265. catch (Exception ex)
  266. {
  267. throw new Exception(ex.Message);
  268. }
  269. finally
  270. {
  271. File.Delete(filePath);
  272. }
  273. }
  274. /// <summary>
  275. /// 批量导入学生总成绩
  276. /// </summary>
  277. /// <param name="filePath"></param>
  278. /// <param name="examPlanId"></param>
  279. /// <returns></returns>
  280. public async Task UploadImportStudentTotalScore(string filePath, int examPlanId)
  281. {
  282. /* ----------------------------------------------------------
  283. * 处理步骤:
  284. * 1.验证表头
  285. * 2.读取数据
  286. * 3.处理班级
  287. * 4.批量插入
  288. ---------------------------------------------------------- */
  289. try
  290. {
  291. #region 1.验证表结构
  292. using FileStream fs = new(filePath, FileMode.Open, FileAccess.Read);
  293. IWorkbook workbook = ExcelUtil.GetWorkbook(filePath, fs);
  294. var sheet = workbook.GetSheetAt(0);
  295. var rows = sheet.GetRowEnumerator();
  296. // 少于2行验证
  297. if (sheet.LastRowNum < 2)
  298. {
  299. //"第一行应为填写说明,第二行应为标题行,请勿修改模板结构。"
  300. return;
  301. }
  302. // 读取表头
  303. rows.MoveNext();
  304. IRow headerRow = (IRow)rows.Current;
  305. int index = 0;
  306. int SAMPLE_TYPE_INDEX = index++;
  307. int SCHOOL_ID_INDEX = index++;
  308. int SCHOOL_NAME_INDEX = index++;
  309. int SCHOOL_BID_INDEX = index++;
  310. int SCHOOL_BNAME_INDEX = index++;
  311. int NAME_INDEX = index++;
  312. int CERT_TYPE_INDEX = index++;
  313. int ID_NUM_INDEX = index++;
  314. int EXAM_NUMBER_INDEX = index++;
  315. int COURSE_COMB_INDEX = index++;
  316. int GRADE_INDEX = index++;
  317. int CLASS_INDEX = index++;
  318. int COURSE_START_INDEX = index;
  319. Dictionary<int, string> headers = new()
  320. {
  321. { SAMPLE_TYPE_INDEX, "抽样类型" },
  322. { SCHOOL_ID_INDEX, "学校ID" },
  323. { SCHOOL_NAME_INDEX, "学校" },
  324. { SCHOOL_BID_INDEX, "校区ID" },
  325. { SCHOOL_BNAME_INDEX, "校区" },
  326. { NAME_INDEX, "姓名" },
  327. { CERT_TYPE_INDEX, "证件类型" },
  328. { ID_NUM_INDEX, "证件号码" },
  329. { EXAM_NUMBER_INDEX, "考号" },
  330. { COURSE_COMB_INDEX, "选科组合" },
  331. { GRADE_INDEX, "年级" },
  332. { CLASS_INDEX, "班级" },
  333. };
  334. List<string> headerErrors = new();
  335. for (int i = 0; i < COURSE_START_INDEX; i++)
  336. {
  337. if (headerRow.GetCell(i)?.ToString() != headers[i])
  338. {
  339. char letter = (char)('A' + i);
  340. headerErrors.Add(letter.ToString());
  341. }
  342. }
  343. if (headerErrors.Any())
  344. {
  345. string columnErrors = string.Join("、", headerErrors);
  346. //result.ErrorMessage.Add($"第1行标题行{columnErrors}列名错误。从A列开始依次应为抽样类型、学校ID、学校、姓名、证件类型、证件号码、考号、年级、班级。");
  347. //return result;
  348. return;
  349. }
  350. //result.StructureCorrect = true;
  351. #endregion
  352. #region 2.读取数据
  353. var examPlan = await _rep.Change<ExamPlan>().DetachedEntities.FirstOrDefaultAsync(t => t.Id == examPlanId) ?? throw Oops.Oh(ErrorCode.E2001, "监测计划");
  354. var examGradeDict = (await _examGradeService.GetListByExamPlanId(examPlanId)).ToDictionary(t => t.Grade.GradeNumber);
  355. var courseDict = (await _rep.Change<Course>().DetachedEntities.ToListAsync()).ToDictionary(t => t.Name);
  356. var examCourses = await _rep.Change<ExamCourse>().DetachedEntities.Where(t => t.ExamPlanId == examPlanId).Select(t => new { t.GradeId, t.CourseId }).ToListAsync();
  357. // 获取需要导入的科目列表
  358. Dictionary<int, Course> courses = new();
  359. for (int gi = COURSE_START_INDEX; gi < headerRow.LastCellNum; gi++)
  360. {
  361. var cn = headerRow.GetCell(gi).ToString() ?? "";
  362. if (string.IsNullOrEmpty(cn))
  363. {
  364. continue;
  365. }
  366. courses.Add(gi, courseDict[cn]);
  367. }
  368. int rn = 1;
  369. List<ExamScoreImportDto> sourceItems = new();
  370. while (rows.MoveNext())
  371. {
  372. rn++;
  373. IRow row = (IRow)rows.Current;
  374. string rv = row.GetCell(0)?.ToString().Trim() ?? "";
  375. if (rv == "")
  376. {
  377. break;
  378. }
  379. var gradeNumber = (short)row.GetCell(GRADE_INDEX).NumericCellValue;
  380. for (int gi = COURSE_START_INDEX; gi < headerRow.LastCellNum; gi++)
  381. {
  382. var course = courses[gi];
  383. var eg = examGradeDict[gradeNumber];
  384. // 跳过未监测科目
  385. if (!examCourses.Any(t => t.GradeId == eg.GradeId && t.CourseId == course.Id))
  386. {
  387. continue;
  388. }
  389. var sbid = row.GetCell(SCHOOL_BID_INDEX)?.NumericCellValue;
  390. var ccid = row.GetCell(COURSE_COMB_INDEX)?.NumericCellValue;
  391. ExamScoreImportDto item = new()
  392. {
  393. RowNumber = rn,
  394. SampleType = (ExamSampleType)row.GetCell(SAMPLE_TYPE_INDEX).NumericCellValue,
  395. SysOrgId = (short)row.GetCell(SCHOOL_ID_INDEX).NumericCellValue,
  396. SysOrgBranchId = sbid > 0 ? (short)sbid : null,
  397. StudentName = StringUtil.ClearWhite(row.GetCell(NAME_INDEX)?.ToString() ?? ""),
  398. CertificateType = (CertificateType)row.GetCell(CERT_TYPE_INDEX).NumericCellValue,
  399. IdNumber = StringUtil.ClearIdNumber(row.GetCell(ID_NUM_INDEX)?.ToString() ?? ""),
  400. ExamNumber = row.GetCell(EXAM_NUMBER_INDEX)?.ToString() ?? "",
  401. GradeNumber = gradeNumber,
  402. ClassNumber = (short)row.GetCell(CLASS_INDEX).NumericCellValue,
  403. CourseId = course.Id,
  404. NceeCourseCombId = ccid > 0 ? (short)ccid : null,
  405. };
  406. string scoreStr = row.GetCell(gi)?.ToString() ?? "";
  407. if (decimal.TryParse(scoreStr, out decimal score))
  408. {
  409. item.Score = score;
  410. }
  411. else if (scoreStr.Contains('特') || scoreStr.Contains('缺'))
  412. {
  413. item.IsExcluded = true;
  414. }
  415. if (item.IdNumber.Length == 18)
  416. {
  417. if (int.TryParse(item.IdNumber.AsSpan(16, 1), out int gn))
  418. {
  419. item.Gender = (short)(gn % 2 == 0 ? 2 : 1);
  420. }
  421. }
  422. item.ExamGradeId = eg.Id;
  423. item.GradeId = eg.GradeId;
  424. item.GradeBeginYear = eg.GradeBeginYear;
  425. item.GradeEndYear = eg.GradeEndYear;
  426. item.SchoolClassId = _schoolClassService.GetSchoolClassId(examPlan.EducationStage, item.SysOrgId, eg.GradeBeginYear, item.ClassNumber);
  427. sourceItems.Add(item);
  428. }
  429. }
  430. workbook.Close();
  431. fs.Close();
  432. #endregion
  433. #region 3.处理班级
  434. var scs = sourceItems.GroupBy(t => t.SchoolClassId).Select(t => new BatchInsertSchoolClassInput
  435. {
  436. Id = t.Key,
  437. SysOrgId = t.FirstOrDefault().SysOrgId,
  438. SysOrgBranchId = t.FirstOrDefault().SysOrgBranchId,
  439. EducationStage = examPlan.EducationStage,
  440. EducationYears = examPlan.EducationYears,
  441. ClassNumber = t.FirstOrDefault().ClassNumber,
  442. GradeBeginYear = t.FirstOrDefault().GradeBeginYear,
  443. GradeEndYear = t.FirstOrDefault().GradeEndYear,
  444. }).Distinct().ToList();
  445. // 插入没有的班级
  446. await _schoolClassService.BatchInsert(scs);
  447. #endregion
  448. #region 4.批量导入
  449. // 清理成绩
  450. string deleteScoreSql = $"DELETE FROM exam_score WHERE exam_plan_id = {examPlanId};";
  451. await _rep.SqlNonQueryAsync(deleteScoreSql);
  452. List<string> selects = new();
  453. var scount = sourceItems.Count;
  454. for (int i = 0; i < scount; i++)
  455. {
  456. var t = sourceItems[i];
  457. string sobid = "NULL";
  458. if (t.SysOrgBranchId.HasValue)
  459. {
  460. sobid = t.SysOrgBranchId.ToString();
  461. }
  462. string ccid = "NULL";
  463. if (t.NceeCourseCombId.HasValue)
  464. {
  465. ccid = t.NceeCourseCombId.ToString();
  466. }
  467. var ied = t.IsExcluded ? 1 : 0;
  468. selects.Add($@"
  469. SELECT {(short)t.SampleType} est, {t.SysOrgId} soid, {sobid} as sobid, {t.GradeId} gid, {examPlan.SemesterId} smid, {t.SchoolClassId} scid, {t.ClassNumber} cn, '{t.ExamNumber}' en, {ccid} ccid, {t.CourseId} cid, {t.Score} s, {ied} ied ");
  470. if ((i + 1) % 500 == 0 || i == scount - 1)
  471. {
  472. string insertSql = $@"
  473. SET @examSampleId = (SELECT MAX(id) FROM exam_sample WHERE exam_plan_id = {examPlanId} AND is_selected = 1);
  474. INSERT INTO exam_score(exam_plan_id, education_stage, exam_sample_type, sys_org_id, sys_org_branch_id, grade_id, semester_id, school_class_id, class_number, exam_student_id, ncee_course_comb_id, course_id, score, is_excluded)
  475. SELECT {examPlanId}, {(short)examPlan.EducationStage}, T1.est, T1.soid, T1.sobid, T1.gid, T1.smid, T1.scid, T1.cn, T2.id, T1.ccid, T1.cid, T1.s, T1.ied
  476. FROM
  477. ({string.Join("UNION ALL", selects)}
  478. ) AS T1
  479. JOIN (SELECT exam_number, exam_student_id AS id FROM exam_sample_student WHERE exam_sample_id = @examSampleId) AS T2
  480. ON T1.en = T2.exam_number;
  481. ";
  482. await _rep.SqlNonQueryAsync(insertSql);
  483. selects.Clear();
  484. }
  485. }
  486. #endregion
  487. #region 5.计算总分和分段
  488. await $@"
  489. -- 更新各科成绩分段
  490. UPDATE exam_score AS T1
  491. JOIN
  492. (
  493. SELECT T1.id, T1.grade_id, T1.course_id, get_exam_score_range_id(T2.exam_score_range_type, T1.score) AS exam_score_range_id
  494. FROM exam_score AS T1
  495. JOIN exam_course AS T2 ON T1.exam_plan_id = T2.exam_plan_id AND T1.grade_id = T2.grade_id AND T1.course_id = T2.course_id
  496. WHERE T1.exam_plan_id = {examPlanId}
  497. ) AS T2 ON T1.id = T2.id
  498. SET T1.exam_score_range_id = T2.exam_score_range_id
  499. WHERE T1.exam_plan_id = {examPlanId};
  500. -- 更新总成绩和分段
  501. DELETE FROM exam_score_total WHERE exam_plan_id = {examPlanId};
  502. INSERT INTO exam_score_total(
  503. exam_plan_id,
  504. education_stage,
  505. exam_sample_type,
  506. sys_org_id,
  507. sys_org_branch_id,
  508. grade_id, semester_id,
  509. school_class_id,
  510. class_number,
  511. exam_student_id,
  512. ncee_course_comb_id,
  513. course_count,
  514. score,
  515. exam_score_range_id,
  516. is_excluded
  517. )
  518. SELECT {examPlanId}, T1.*, get_exam_score_range_id(T2.exam_score_range_type, T1.score) AS exam_score_range_id, 0
  519. FROM
  520. (
  521. SELECT
  522. education_stage,
  523. exam_sample_type,
  524. sys_org_id,
  525. sys_org_branch_id,
  526. grade_id, semester_id,
  527. school_class_id,
  528. class_number,
  529. exam_student_id,
  530. ncee_course_comb_id,
  531. COUNT(1) AS course_count,
  532. SUM(IFNULL(score, 0)) AS score
  533. FROM exam_score
  534. WHERE exam_plan_id = {examPlanId}
  535. GROUP BY education_stage, exam_sample_type, sys_org_id, sys_org_branch_id, grade_id, semester_id, school_class_id, class_number, exam_student_id, ncee_course_comb_id
  536. ) AS T1
  537. JOIN
  538. (
  539. SELECT grade_id, exam_score_range_type FROM exam_grade WHERE exam_plan_id = {examPlanId}
  540. ) AS T2 ON T1.grade_id = T2.grade_id;
  541. ".SetCommandTimeout(6000).SqlNonQueryAsync();
  542. #endregion
  543. }
  544. catch (Exception ex)
  545. {
  546. throw new Exception(ex.Message);
  547. }
  548. finally
  549. {
  550. File.Delete(filePath);
  551. }
  552. }
  553. /// <summary>
  554. /// 上传并合并小题成绩导出
  555. /// </summary>
  556. /// <param name="filePath"></param>
  557. /// <param name="examPlanId"></param>
  558. /// <returns></returns>
  559. /// <exception cref="Exception"></exception>
  560. public async Task<(string, byte[])> UploadImportStudentMinorScore(string filePath, int examPlanId)
  561. {
  562. var examPlan = await _rep.Change<ExamPlan>().DetachedEntities.FirstOrDefaultAsync(t => t.Id == examPlanId) ?? throw Oops.Oh(ErrorCode.E2001, "监测计划");
  563. // 解压输出目录
  564. string unzipPath = Path.Combine(FileUtil.GetTempFileRoot(), Path.GetFileNameWithoutExtension(filePath));
  565. Directory.CreateDirectory(unzipPath);
  566. // 临时存放目录
  567. string outputRoot = Path.Combine(FileUtil.GetTempFileRoot(), $"{Guid.NewGuid()}");
  568. Directory.CreateDirectory(outputRoot);
  569. string outputFilePath = Path.Combine(outputRoot, $"{examPlan.Name}-区校合并-小题成绩");
  570. Directory.CreateDirectory(outputFilePath);
  571. try
  572. {
  573. List<ExamScoreMinorFileInfo> fileInfos = new();
  574. var gradeDict = (await _rep.Change<Grade>().DetachedEntities.Where(t => t.EducationStage == examPlan.EducationStage).ToListAsync()).ToDictionary(t => t.Name);
  575. var courseDict = (await _rep.Change<Course>().DetachedEntities.ToListAsync()).ToDictionary(t => t.Name);
  576. #region 1.读取文件信息
  577. ZipFile.ExtractToDirectory(filePath, unzipPath, System.Text.Encoding.GetEncoding("GBK"), true);
  578. var sampleTypePaths = Directory.GetDirectories(unzipPath);
  579. foreach (var stpath in sampleTypePaths)
  580. {
  581. var tn = Path.GetFileNameWithoutExtension(stpath).Split("-");
  582. ExamSampleType est;
  583. if (int.TryParse(tn[0], out int estInt))
  584. {
  585. est = (ExamSampleType)estInt;
  586. }
  587. else
  588. {
  589. throw new ArgumentException("监测抽样类型错误");
  590. }
  591. var scoreFiles = Directory.GetFiles(stpath).Where(t => t.EndsWith(".xlsx") || t.EndsWith(".xls")).Where(t => !t.StartsWith("~"));
  592. foreach (var scoreFile in scoreFiles)
  593. {
  594. var fn = Path.GetFileNameWithoutExtension(scoreFile).Split("-");
  595. var gradeName = fn[1];
  596. var grade = gradeDict[gradeName];
  597. var courseName = fn[2];
  598. var course = courseDict[courseName];
  599. fileInfos.Add(new()
  600. {
  601. ExamSampleType = est,
  602. FilePath = scoreFile,
  603. GradeId = grade.Id,
  604. Grade = grade,
  605. CourseId = course.Id,
  606. Course = course,
  607. });
  608. }
  609. }
  610. #endregion
  611. #region 2.合并文件
  612. var cfiles = fileInfos.Where(t => t.ExamSampleType == ExamSampleType.DISTRICT);
  613. foreach (var cfile in cfiles)
  614. {
  615. var qminors = await _rep.Change<ExamPaperQuestionMinor>().DetachedEntities.Where(t => t.ExamPaper.ExamPlanId == examPlanId && t.ExamPaper.CourseId == cfile.CourseId && t.ExamPaper.GradeId == cfile.GradeId && t.IsLeaf == true).ToListAsync();
  616. var examSampleStudents = await _rep.Change<ExamSampleStudent>().DetachedEntities
  617. .Where(t => t.ExamSample.ExamPlanId == examPlanId && t.ExamSample.IsSelected == true && t.ExamStudent.GradeId == cfile.GradeId)
  618. .Select(t => new { t.ExamNumber, t.ExamStudentId, t.ExamStudent.SysOrgId })
  619. .ToListAsync();
  620. var sfile = fileInfos.FirstOrDefault(t => t.ExamSampleType == ExamSampleType.SCHOOL_EXAM && t.GradeId == cfile.GradeId && t.CourseId == cfile.CourseId) ?? throw new ArgumentNullException($"{cfile}对应校考小题成绩未找到");
  621. // 区文件
  622. using FileStream c_fs = new(cfile.FilePath, FileMode.Open, FileAccess.Read);
  623. IWorkbook c_workbook = ExcelUtil.GetWorkbook(filePath, c_fs);
  624. var c_sheet = c_workbook.GetSheetAt(0);
  625. var c_rows = c_sheet.GetRowEnumerator();
  626. // 输出文件
  627. IWorkbook o_workbook = new XSSFWorkbook();
  628. ISheet o_sheet = o_workbook.CreateSheet();
  629. var o_cellStyles = _exportExcelService.GetCellStyle(o_workbook);
  630. int o_rowNum = 0;
  631. IRow o_headerRow = o_sheet.CreateRow(o_rowNum++);
  632. // 标题行
  633. Dictionary<int, ExamPaperQuestionMinor> colMinor = new();
  634. c_rows.MoveNext();
  635. var c_headerRow = (IRow)c_rows.Current;
  636. int colNum = c_headerRow.LastCellNum;
  637. for (int ci = 0; ci < colNum; ci++)
  638. {
  639. string colName = c_headerRow.GetCell(ci)?.ToString() ?? "";
  640. _exportExcelService.AddCell(c_headerRow.GetCell(ci)?.ToString(), o_headerRow, ci, o_cellStyles.CenterCellStyle, o_sheet, width: ci == 1 ? 12 : ci == 2 ? 30 : null);
  641. var qm = qminors.FirstOrDefault(t => t.ColumnName == colName);
  642. if (qm != null)
  643. {
  644. colMinor.Add(ci, qm);
  645. }
  646. }
  647. // 所有小题成绩列表
  648. List<ExamScoreMinorImportDto> items = new();
  649. // 区文件写入
  650. while (c_rows.MoveNext())
  651. {
  652. var row = (IRow)c_rows.Current;
  653. var c0 = row.GetCell(0);
  654. if (c0 == null || c0.ToString() == "")
  655. {
  656. break;
  657. }
  658. ExamScoreMinorImportDto item = new();
  659. IRow o_row = o_sheet.CreateRow(o_rowNum++);
  660. for (int tci = 0; tci < colNum; tci++)
  661. {
  662. var cell = row.GetCell(tci);
  663. if (cell == null)
  664. {
  665. continue;
  666. }
  667. if (cell.CellType == CellType.Numeric)
  668. {
  669. _exportExcelService.AddCell(cell.NumericCellValue, o_row, tci, o_cellStyles.CenterCellStyle, o_sheet);
  670. }
  671. else
  672. {
  673. _exportExcelService.AddCell(cell.ToString(), o_row, tci, o_cellStyles.CenterCellStyle, o_sheet);
  674. }
  675. if (tci == 1)
  676. {
  677. var examNumber = cell.ToString();
  678. var stu = examSampleStudents.FirstOrDefault(t => t.ExamNumber == examNumber);
  679. if (stu != null)
  680. {
  681. item.ExamStudentId = stu.ExamStudentId;
  682. item.SysOrgId = stu.SysOrgId;
  683. }
  684. }
  685. else if (tci >= 7 && colMinor.TryGetValue(tci, out ExamPaperQuestionMinor cm))
  686. {
  687. if (cell.CellType == CellType.Numeric)
  688. {
  689. item.Score = (decimal)cell.NumericCellValue;
  690. }
  691. else
  692. {
  693. if (decimal.TryParse(cell.ToString(), out decimal s))
  694. {
  695. item.Score = s;
  696. }
  697. }
  698. item.StarScore = cm.Score == 0 ? 0 : item.Score / cm.Score;
  699. if (item.ExamStudentId != 0)
  700. {
  701. items.Add(new()
  702. {
  703. ExamStudentId = item.ExamStudentId,
  704. SysOrgId = item.SysOrgId,
  705. ExamPaperQuestionMinorId = cm.Id,
  706. Score = item.Score,
  707. StarScore = item.StarScore
  708. });
  709. }
  710. }
  711. }
  712. }
  713. // 校文件
  714. using FileStream s_fs = new(sfile.FilePath, FileMode.Open, FileAccess.Read);
  715. IWorkbook s_workbook = ExcelUtil.GetWorkbook(sfile.FilePath, s_fs);
  716. var s_sheet = s_workbook.GetSheetAt(0);
  717. var s_rows = s_sheet.GetRowEnumerator();
  718. s_rows.MoveNext();
  719. // 校文件写入
  720. while (s_rows.MoveNext())
  721. {
  722. var row = (IRow)s_rows.Current;
  723. var c0 = row.GetCell(0);
  724. if (c0 == null || c0.ToString() == "")
  725. {
  726. break;
  727. }
  728. ExamScoreMinorImportDto item = new();
  729. IRow o_row = o_sheet.CreateRow(o_rowNum++);
  730. for (int tci = 0; tci < colNum; tci++)
  731. {
  732. var cell = row.GetCell(tci);
  733. if (cell == null)
  734. {
  735. continue;
  736. }
  737. if (cell.CellType == CellType.Numeric)
  738. {
  739. _exportExcelService.AddCell(cell.NumericCellValue, o_row, tci, o_cellStyles.CenterCellStyle, o_sheet);
  740. }
  741. else
  742. {
  743. _exportExcelService.AddCell(cell.ToString(), o_row, tci, o_cellStyles.CenterCellStyle, o_sheet);
  744. }
  745. if (tci == 1)
  746. {
  747. var examNumber = cell.ToString();
  748. var stu = examSampleStudents.FirstOrDefault(t => t.ExamNumber == examNumber);
  749. if (stu != null)
  750. {
  751. item.ExamStudentId = stu.ExamStudentId;
  752. item.SysOrgId = stu.SysOrgId;
  753. }
  754. }
  755. else if (tci >= 7 && colMinor.TryGetValue(tci, out ExamPaperQuestionMinor cm))
  756. {
  757. if (cell.CellType == CellType.Numeric)
  758. {
  759. item.Score = (decimal)cell.NumericCellValue;
  760. }
  761. else
  762. {
  763. if (decimal.TryParse(cell.ToString(), out decimal s))
  764. {
  765. item.Score = s;
  766. }
  767. }
  768. item.StarScore = cm.Score == 0 ? 0 : item.Score / cm.Score;
  769. if (item.ExamStudentId != 0)
  770. {
  771. items.Add(new()
  772. {
  773. ExamStudentId = item.ExamStudentId,
  774. SysOrgId = item.SysOrgId,
  775. ExamPaperQuestionMinorId = cm.Id,
  776. Score = item.Score,
  777. StarScore = item.StarScore
  778. });
  779. }
  780. }
  781. }
  782. }
  783. o_sheet.CreateFreezePane(0, 1);
  784. MemoryStream o_ms = new();
  785. o_workbook.Write(o_ms, false);
  786. o_ms.Flush();
  787. await File.WriteAllBytesAsync(Path.Combine(outputFilePath, $"{examPlan.EducationStage.GetDescription()}-{cfile.Grade.Name}-{cfile.Course.Name}-小题成绩.xlsx"), o_ms.ToArray());
  788. #region 批量导入
  789. // 清理成绩
  790. string deleteScoreSql = $"DELETE FROM exam_score_minor WHERE exam_plan_id = {examPlanId} AND grade_id = {cfile.GradeId} AND course_id = {cfile.CourseId};";
  791. //await _rep.SqlNonQueryAsync(deleteScoreSql);
  792. await deleteScoreSql.SetCommandTimeout(60000).SqlNonQueryAsync();
  793. List<string> values = new();
  794. var scount = items.Count;
  795. for (int i = 0; i < scount; i++)
  796. {
  797. var item = items[i];
  798. values.Add($"({examPlanId},{item.SysOrgId},{item.ExamStudentId},{cfile.GradeId},{cfile.CourseId},{item.ExamPaperQuestionMinorId},{item.Score},{item.StarScore})");
  799. if ((i + 1) % 2000 == 0 || i == scount - 1)
  800. {
  801. string insertSql = $"INSERT INTO exam_score_minor(exam_plan_id,sys_org_id,exam_student_id,grade_id,course_id,exam_paper_question_minor_id,score,star_score) VALUES {string.Join(",", values)}";
  802. //await _rep.SqlNonQueryAsync(insertSql);
  803. await insertSql.SetCommandTimeout(60000).SqlNonQueryAsync();
  804. values.Clear();
  805. }
  806. }
  807. #endregion
  808. }
  809. #endregion
  810. string outFileName = $"{examPlan.Name}-区校合并-小题成绩.zip";
  811. string oFilePath = Path.Combine(outputRoot, outFileName);
  812. ICSharpCode.SharpZipLib.Zip.FastZip zip = new();
  813. zip.CreateZip(oFilePath, outputFilePath, true, string.Empty);
  814. var retBytes = await File.ReadAllBytesAsync(oFilePath);
  815. return (outFileName, retBytes);
  816. }
  817. catch (Exception ex)
  818. {
  819. throw new Exception(ex.Message);
  820. }
  821. finally
  822. {
  823. File.Delete(filePath);
  824. Directory.Delete(unzipPath, true);
  825. Directory.Delete(outputRoot, true);
  826. }
  827. }
  828. }