void ImportNewStudentsUpdateRecord_BeginValidate(object sender, BeginValidateEventArgs e) { #region 整理異動代號及類別對照 updateCodeMapping = new Dictionary <string, string>(); foreach (SHUpdateCodeMappingInfo var in SHUpdateCodeMapping.SelectAll()) { if (!updateCodeMapping.ContainsKey(var.Code)) { updateCodeMapping.Add(var.Code, var.Type); } } #endregion _NewStudentUpdateRecordInfoList = new Dictionary <string, SHUpdateRecordRecord>(); List <SHStudentRecord> students = SHStudent.SelectByIDs(e.List); foreach (SHStudentRecord stu in students) { if (!_NewStudentUpdateRecordInfoList.ContainsKey(stu.ID)) { _NewStudentUpdateRecordInfoList.Add(stu.ID, null); } else { _NewStudentUpdateRecordInfoList[stu.ID] = null; } foreach (SHUpdateRecordRecord uinfo in SHUpdateRecord.SelectByStudentID(stu.ID)) { if (uinfo.UpdateType == Type) { _NewStudentUpdateRecordInfoList[stu.ID] = uinfo; break; } } } }
void _bgWorkerLoad_DoWork(object sender, DoWorkEventArgs e) { // 取得就學生畢業異動資料 _StudHasGraduateRecDict.Clear(); List <SHUpdateRecordRecord> recList = SHUpdateRecord.SelectByStudentIDs(_StudentIDList); foreach (SHUpdateRecordRecord rec in recList) { // 不是畢業異動跳過 if (rec.UpdateCode != "501") { continue; } if (!_StudHasGraduateRecDict.ContainsKey(rec.StudentID)) { _StudHasGraduateRecDict.Add(rec.StudentID, rec); } } // 取得最後一筆異動 _StudLastupdateRecDict.Clear(); foreach (string sid in _StudentIDList) { List <SHUpdateRecordRecord> recL = (from data in recList where data.StudentID == sid && data.ADDate.Trim() != "" orderby DateTime.Parse(data.ADDate) descending, int.Parse(data.ID) descending select data).ToList(); if (recL.Count > 0) { SHUpdateRecordRecord r1 = recL[0]; if (!_StudLastupdateRecDict.ContainsKey(r1.StudentID)) { _StudLastupdateRecDict.Add(r1.StudentID, r1); } } } // 學生資料 _StudentDict.Clear(); foreach (SHStudentRecord rec in SHStudent.SelectByIDs(_StudentIDList)) { _StudentDict.Add(rec.ID, rec); } // 畢業證書 _LeaveInfoRecordDict.Clear(); foreach (SHLeaveInfoRecord rec in SHLeaveInfo.SelectByStudentIDs(_StudentIDList)) { if (!_LeaveInfoRecordDict.ContainsKey(rec.RefStudentID)) { _LeaveInfoRecordDict.Add(rec.RefStudentID, rec); } } // 班級 _ClassRecDict.Clear(); foreach (SHClassRecord rec in SHClass.SelectAll()) { if (!_ClassRecDict.ContainsKey(rec.ID)) { _ClassRecDict.Add(rec.ID, rec); } } // 科別 _DeptRecDict.Clear(); foreach (SHDepartmentRecord rec in SHDepartment.SelectAll()) { if (!_DeptRecDict.ContainsKey(rec.ID)) { _DeptRecDict.Add(rec.ID, rec); } } }
void _bgw_DoWork(object sender, DoWorkEventArgs e) { Document document = new Document(); Byte[] template = (custConfigs[current].Template != null) //單頁範本 ? custConfigs[current].Template.ToBinary() : new Campus.Report.ReportTemplate(Properties.Resources.證明書範本, Campus.Report.TemplateType.Word).ToBinary(); List <string> ids = K12.Presentation.NLDPanels.Student.SelectedSource; List <SHStudentRecord> srl = SHStudent.SelectByIDs(ids); //離校資訊 Dictionary <string, SHLeaveInfoRecord> dshlir = SHLeaveInfo.SelectByStudentIDs(ids).ToDictionary(x => x.RefStudentID, x => x); //畢業異動 Dictionary <string, SHUpdateRecordRecord> dshurr = new Dictionary <string, SHUpdateRecordRecord>(); foreach (SHUpdateRecordRecord shurr in SHUpdateRecord.SelectByStudentIDs(ids)) { if (shurr.UpdateCode == "501") { if (dshurr.ContainsKey(shurr.StudentID)) { if (dshurr[shurr.StudentID].UpdateDate.CompareTo(shurr.UpdateDate) == 1) { dshurr[shurr.StudentID] = shurr; } } else { dshurr.Add(shurr.StudentID, shurr); } } } //入學照片 Dictionary <string, string> dphoto_p = K12.Data.Photo.SelectFreshmanPhoto(K12.Presentation.NLDPanels.Student.SelectedSource); Dictionary <string, string> dphoto_g = K12.Data.Photo.SelectGraduatePhoto(K12.Presentation.NLDPanels.Student.SelectedSource); //科別中英文對照表 Dictionary <string, string> dic_dept_ch_en = new Dictionary <string, string>(); XmlElement Data = SmartSchool.Customization.Data.SystemInformation.Configuration["科別中英文對照表"]; foreach (XmlElement var in Data) { if (!dic_dept_ch_en.ContainsKey(var.GetAttribute("Chinese"))) { dic_dept_ch_en.Add(var.GetAttribute("Chinese"), var.GetAttribute("English")); } } Dictionary <string, object> mailmerge = new Dictionary <string, object>(); string 校內字號 = textBoxX1.Text, 校內字號英文 = textBoxX2.Text, 校長姓名 = "", 校長姓名英文 = ""; if (K12.Data.School.Configuration["學校資訊"] != null && K12.Data.School.Configuration["學校資訊"].PreviousData.SelectSingleNode("ChancellorChineseName") != null) { 校長姓名 = K12.Data.School.Configuration["學校資訊"].PreviousData.SelectSingleNode("ChancellorChineseName").InnerText; } if (K12.Data.School.Configuration["學校資訊"] != null && K12.Data.School.Configuration["學校資訊"].PreviousData.SelectSingleNode("ChancellorChineseName") != null) { 校長姓名英文 = K12.Data.School.Configuration["學校資訊"].PreviousData.SelectSingleNode("ChancellorEnglishName").InnerText; } Document each; foreach (SHStudentRecord sr in srl) { mailmerge.Clear(); mailmerge.Add("學校全銜", School.ChineseName); mailmerge.Add("學校英文全銜", School.EnglishName); mailmerge.Add("目前學期", School.DefaultSemester); mailmerge.Add("目前學年度", School.DefaultSchoolYear); mailmerge.Add("校長姓名", 校長姓名); mailmerge.Add("校長姓名英文", 校長姓名英文); mailmerge.Add("民國年", DateTime.Today.Year - 1911); mailmerge.Add("英文年", DateTime.Today.Year); mailmerge.Add("月", DateTime.Today.Month); mailmerge.Add("英文月", DateTime.Today.ToString("MMMM", new System.Globalization.CultureInfo("en-US"))); mailmerge.Add("英文月3", DateTime.Today.ToString("MMM", new System.Globalization.CultureInfo("en-US"))); mailmerge.Add("日上標", daySuffix(DateTime.Today.Day.ToString())); mailmerge.Add("日", DateTime.Today.Day); mailmerge.Add("校內字號", 校內字號); mailmerge.Add("校內字號英文", 校內字號英文); #region 學生資料 mailmerge.Add("學生姓名", sr.Name); mailmerge.Add("學生英文姓名", sr.EnglishName); mailmerge.Add("學生身分證號", sr.IDNumber); SHClassRecord tmpcr; if ((tmpcr = sr.Class) != null) { mailmerge.Add("學生目前班級", tmpcr.Name); mailmerge.Add("學生目前年級", tmpcr.GradeYear); if (tmpcr.Department != null) { mailmerge.Add("學生目前科別", tmpcr.Department.Name); } } mailmerge.Add("學生目前座號", sr.StudentNumber); if (sr.Birthday.HasValue) { mailmerge.Add("學生生日民國年", sr.Birthday.Value.Year - 1911); mailmerge.Add("學生生日英文年", sr.Birthday.Value.Year); mailmerge.Add("學生生日月", sr.Birthday.Value.Month); mailmerge.Add("學生生日英文月", sr.Birthday.Value.ToString("MMMM", new System.Globalization.CultureInfo("en-US"))); mailmerge.Add("學生生日英文月3", sr.Birthday.Value.ToString("MMM", new System.Globalization.CultureInfo("en-US"))); mailmerge.Add("學生生日上標", daySuffix(sr.Birthday.Value.Day.ToString())); mailmerge.Add("學生生日日", sr.Birthday.Value.Day); } if (dphoto_p.ContainsKey(sr.ID)) { mailmerge.Add("入學照片1吋", dphoto_p[sr.ID]); mailmerge.Add("入學照片2吋", dphoto_p[sr.ID]); } if (dphoto_g.ContainsKey(sr.ID)) { mailmerge.Add("畢業照片1吋", dphoto_g[sr.ID]); mailmerge.Add("畢業照片2吋", dphoto_g[sr.ID]); } //畢業資訊 if (dshlir.ContainsKey(sr.ID)) { mailmerge["畢業資訊西元年"] = dshlir[sr.ID].SchoolYear + 1911; mailmerge["畢業資訊學年度"] = dshlir[sr.ID].SchoolYear; mailmerge["畢業資訊證書字號"] = dshlir[sr.ID].DiplomaNumber; mailmerge["畢業資訊證書字號數字"] = getCertificateNumberNumber(dshlir[sr.ID].DiplomaNumber); mailmerge["畢業資訊科別中文"] = dshlir[sr.ID].DepartmentName; string tmp_dept = dshlir[sr.ID].DepartmentName; mailmerge["畢業資訊科別英文"] = (tmp_dept != null && dic_dept_ch_en.ContainsKey(tmp_dept)) ? dic_dept_ch_en[tmp_dept] : ""; } //畢業異動 if (dshurr.ContainsKey(sr.ID)) { //int ExpectGraduateSchoolYear; //if (int.TryParse(dshurr[sr.ID].ExpectGraduateSchoolYear, out ExpectGraduateSchoolYear)) // mailmerge["畢業異動西元年"] = ExpectGraduateSchoolYear + 1911; if (!string.IsNullOrEmpty(dshurr[sr.ID].UpdateDate)) { int ADYear; int.TryParse(dshurr[sr.ID].UpdateDate.Split('/')[0], out ADYear); mailmerge["畢業異動西元年"] = ADYear; int republicYaer; if (ADYear > 1911) { republicYaer = ADYear - 1911; mailmerge["畢業異動民國年"] = republicYaer; } int UpdateDateMonth; int.TryParse(dshurr[sr.ID].UpdateDate.Split('/')[1], out UpdateDateMonth); int UpdateDateDate; int.TryParse(dshurr[sr.ID].UpdateDate.Split('/')[2], out UpdateDateDate); mailmerge["畢業異動月"] = UpdateDateMonth; mailmerge["畢業異動日"] = UpdateDateDate; } mailmerge["畢業異動學年度"] = dshurr[sr.ID].ExpectGraduateSchoolYear; mailmerge["畢業異動證書字號"] = dshurr[sr.ID].GraduateCertificateNumber; mailmerge["畢業異動證書字號數字"] = getCertificateNumberNumber(dshurr[sr.ID].GraduateCertificateNumber); mailmerge["畢業異動科別中文"] = dshurr[sr.ID].Department; string tmp_dept = dshurr[sr.ID].Department; mailmerge["畢業異動科別英文"] = (tmp_dept != null && dic_dept_ch_en.ContainsKey(tmp_dept)) ? dic_dept_ch_en[tmp_dept] : ""; } #endregion each = new Document(new MemoryStream(template)); //each.MailMerge.CleanupOptions = Aspose.Words.Reporting.MailMergeCleanupOptions.RemoveUnusedFields; each.MailMerge.FieldMergingCallback = new merge(); each.MailMerge.Execute(mailmerge.Keys.ToArray(), mailmerge.Values.ToArray()); each.MailMerge.DeleteFields(); document.Sections.Add(document.ImportNode(each.FirstSection, true)); } document.Sections.RemoveAt(0); e.Result = document; }
void _bgWorker_DoWork(object sender, DoWorkEventArgs e) { _DataTable = new DataTable(); // 新增 DataTable Columns AddTableColumns(); _bgWorker.ReportProgress(1); // word 資料合併 Document doc = new Document(); doc.Sections.Clear(); // 取得資料 _StudentRecDict.Clear(); foreach (SHStudentRecord rec in SHStudent.SelectByIDs(_StudentIDList)) { _StudentRecDict.Add(rec.ID, rec); } _PhoneRecDict.Clear(); foreach (SHPhoneRecord rec in SHPhone.SelectByStudentIDs(_StudentIDList)) { _PhoneRecDict.Add(rec.RefStudentID, rec); } // 入學照片 _PhotoPDict.Clear(); _PhotoPDict = K12.Data.Photo.SelectFreshmanPhoto(_StudentIDList); // 畢業照片 _PhotoGDict.Clear(); _PhotoGDict = K12.Data.Photo.SelectGraduatePhoto(_StudentIDList); _ParentRecDict.Clear(); foreach (SHParentRecord rec in SHParent.SelectByStudentIDs(_StudentIDList)) { _ParentRecDict.Add(rec.RefStudentID, rec); } _AddressRecDict.Clear(); foreach (SHAddressRecord rec in SHAddress.SelectByStudentIDs(_StudentIDList)) { _AddressRecDict.Add(rec.RefStudentID, rec); } _ClassRecDict.Clear(); foreach (SHClassRecord rec in SHClass.SelectAll()) { _ClassRecDict.Add(rec.ID, rec); } // 學校名稱 string SchoolName = K12.Data.School.ChineseName; _bgWorker.ReportProgress(30); // 開始填入資料 foreach (string StudID in _StudentIDList) { DataRow row = _DataTable.NewRow(); row["學校名稱"] = SchoolName; if (_StudentRecDict.ContainsKey(StudID)) { if (_StudentRecDict[StudID].Department != null) { row["科別"] = _StudentRecDict[StudID].Department.FullName; } else { row["科別"] = ""; } row["學號"] = _StudentRecDict[StudID].StudentNumber; // 處理班級 if (_ClassRecDict.ContainsKey(_StudentRecDict[StudID].RefClassID)) { row["班級"] = _ClassRecDict[_StudentRecDict[StudID].RefClassID].Name; } row["條碼"] = _StudentRecDict[StudID].StudentNumber; row["姓名"] = _StudentRecDict[StudID].Name; row["英文姓名"] = _StudentRecDict[StudID].EnglishName; row["性別"] = _StudentRecDict[StudID].Gender; row["身分證字號"] = _StudentRecDict[StudID].IDNumber; if (_StudentRecDict[StudID].Birthday.HasValue) { DateTime dtb = _StudentRecDict[StudID].Birthday.Value; row["生日"] = dtb.Year + "/" + dtb.Month + "/" + dtb.Day; row["生日2"] = (dtb.Year - 1911) + "/" + dtb.Month + "/" + dtb.Day; } else { row["生日"] = ""; row["生日2"] = ""; } } if (_PhotoPDict.ContainsKey(StudID)) { row["照片"] = _PhotoPDict[StudID]; row["照片2"] = _PhotoPDict[StudID]; } if (_PhotoGDict.ContainsKey(StudID)) { row["畢業照片"] = _PhotoGDict[StudID]; row["畢業照片2"] = _PhotoGDict[StudID]; } if (_PhoneRecDict.ContainsKey(StudID)) { row["戶籍電話"] = _PhoneRecDict[StudID].Permanent; row["聯絡電話"] = _PhoneRecDict[StudID].Contact; } if (_ParentRecDict.ContainsKey(StudID)) { row["監護人電話"] = _ParentRecDict[StudID].CustodianPhone; row["監護人姓名"] = _ParentRecDict[StudID].CustodianName; row["父親電話"] = _ParentRecDict[StudID].FatherPhone; row["父親姓名"] = _ParentRecDict[StudID].FatherName; row["母親電話"] = _ParentRecDict[StudID].MotherPhone; row["母親姓名"] = _ParentRecDict[StudID].MotherName; } if (_AddressRecDict.ContainsKey(StudID)) { row["戶籍地址"] = _AddressRecDict[StudID].PermanentAddress; row["聯絡地址"] = _AddressRecDict[StudID].MailingAddress; } _DataTable.Rows.Add(row); } _bgWorker.ReportProgress(70); int page = 1; count = 0; List <string> mapNameList = _Config.Template.ToDocument().MailMerge.GetFieldNames().ToList(); foreach (string str in mapNameList) { if (str == "姓名") { count++; } } for (int i = 1; i <= _StudentIDList.Count; i++) { if (i % count == 0 && i >= count) { page++; } } // 當人數與一頁個數相同,只有一頁 if (count == _StudentIDList.Count) { page = 1; } for (int i = 1; i <= page; i++) { Document document = new Document(); document = _Config.Template.ToDocument(); doc.Sections.Add(doc.ImportNode(document.Sections[0], true)); } doc.MailMerge.MergeField += new Aspose.Words.Reporting.MergeFieldEventHandler(MailMerge_MergeField); doc.MailMerge.Execute(_DataTable); doc.MailMerge.RemoveEmptyParagraphs = true; doc.MailMerge.DeleteFields(); //doc.Sections.Add(doc.ImportNode(document.Sections[0], true)); _bgWorker.ReportProgress(95); e.Result = doc; }
void _bgWorker_DoWork(object sender, DoWorkEventArgs e) { _bgWorker.ReportProgress(10); _SchoolCode = K12.Data.School.Code; // 讀取缺勤名冊樣板 _wb = new Workbook(new MemoryStream(Properties.Resources.缺勤紀錄名冊樣板)); Worksheet wst1 = _wb.Worksheets["缺勤紀錄名冊封面"]; Worksheet wst2 = _wb.Worksheets["缺勤紀錄名冊"]; List <SHStudentRecord> StudentRecList = SHStudent.SelectByIDs(_StudentIDList); Dictionary <string, SHStudentRecord> StudentRecDict = new Dictionary <string, SHStudentRecord>(); foreach (SHStudentRecord rec in StudentRecList) { StudentRecDict.Add(rec.ID, rec); } _bgWorker.ReportProgress(30); List <SHAttendanceRecord> AttendanceList = SHAttendance.SelectBySchoolYearAndSemester(StudentRecList, _SchoolYear, _Semester); Dictionary <string, StudAttendanceRec> AttendanceDict = new Dictionary <string, StudAttendanceRec>(); foreach (SHAttendanceRecord rec in AttendanceList) { foreach (AttendancePeriod per in rec.PeriodDetail) { if (_AbsenceDict.ContainsKey(per.AbsenceType) && _PeriodList.Contains(per.Period)) { string strDate = Utility.ConvertChDateString(rec.OccurDate); string key = rec.RefStudentID + "_" + strDate + "_" + per.AbsenceType; if (!AttendanceDict.ContainsKey(key)) { AttendanceDict.Add(key, new StudAttendanceRec()); AttendanceDict[key].StudentID = rec.RefStudentID; AttendanceDict[key].BeginDate = strDate; AttendanceDict[key].EndDate = strDate; // 代碼轉換 if (_AbsenceDict.ContainsKey(per.AbsenceType)) { AttendanceDict[key].AttendType = _AbsenceDict[per.AbsenceType]; } AttendanceDict[key].AttendTypeCount = 0; } AttendanceDict[key].AttendTypeCount++; } } } _bgWorker.ReportProgress(60); // 讀取資料 List <StudAttendanceRec> StudAttendanceRecList = AttendanceDict.Values.ToList(); // 填入身分證、生日 foreach (StudAttendanceRec rec in StudAttendanceRecList) { if (StudentRecDict.ContainsKey(rec.StudentID)) { rec.IDNumber = StudentRecDict[rec.StudentID].IDNumber.ToUpper(); rec.BirthDate = Utility.ConvertChDateString(StudentRecDict[rec.StudentID].Birthday); } } // 排序 StudAttendanceRecList = (from data in StudAttendanceRecList orderby data.IDNumber, data.BeginDate, data.AttendType select data).ToList(); _bgWorker.ReportProgress(80); // 寫入資料 名冊封面 wst1.Cells[1, 0].PutValue(_SchoolCode); wst1.Cells[1, 1].PutValue(_SchoolYear); wst1.Cells[1, 2].PutValue(_Semester); wst1.Cells[1, 3].PutValue(_DocType); // 名冊內容 // 身分證號,出生日期,缺勤種類代碼,缺勤節數,缺勤起始日期,缺勤結束日期 int rowIdx = 1; foreach (StudAttendanceRec rec in StudAttendanceRecList) { wst2.Cells[rowIdx, 0].PutValue(rec.IDNumber); wst2.Cells[rowIdx, 1].PutValue(rec.BirthDate); wst2.Cells[rowIdx, 2].PutValue(rec.AttendType); wst2.Cells[rowIdx, 3].PutValue(rec.AttendTypeCount); wst2.Cells[rowIdx, 4].PutValue(rec.BeginDate); wst2.Cells[rowIdx, 5].PutValue(rec.EndDate); rowIdx++; } _bgWorker.ReportProgress(100); }
void bkwNotPassComputer_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { SmartSchool.Customization.PlugIn.Global.SetStatusBarMessage(_Title + " 檔案儲存中。", 100); if (e.Error == null) { Workbook report = (Workbook)((object[])e.Result)[0]; bool overLimit = (bool)((object[])e.Result)[2]; //儲存 Excel #region 儲存 Excel string path = (string)((object[])e.Result)[1]; if (File.Exists(path)) { bool needCount = true; try { File.Delete(path); needCount = false; } catch { } int i = 1; while (needCount) { string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path); if (!File.Exists(newPath)) { path = newPath; break; } else { try { File.Delete(newPath); path = newPath; break; } catch { } } } } try { File.Create(path).Close(); } catch { SaveFileDialog sd = new SaveFileDialog(); sd.Title = "另存新檔"; sd.FileName = Path.GetFileNameWithoutExtension(path) + ".xls"; sd.Filter = "Excel檔案 (*.xls)|*.xls|所有檔案 (*.*)|*.*"; if (sd.ShowDialog() == DialogResult.OK) { try { File.Create(sd.FileName); path = sd.FileName; } catch { MsgBox.Show("指定路徑無法存取。", "建立檔案失敗", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } report.Save(path, FileFormatType.Excel2003); #endregion SmartSchool.Customization.PlugIn.Global.SetStatusBarMessage(_Title + "完成。"); #region Log List <SHStudentRecord> list = SHStudent.SelectByIDs(StudIDList); foreach (SHStudentRecord each in list) { if (each.Class != null) { SB.AppendLine("姓名「" + each.Name + "」班級「" + each.Class.Name + "」座號「" + each.SeatNo + "」學號「" + each.StudentNumber + "」。"); } else { SB.AppendLine("姓名「" + each.Name + "」學號「" + each.StudentNumber + "」。"); } } ApplicationLog.Log("學務系統.匯出", _Title, "已進行「" + _Title + "」操作。\n" + SB.ToString()); #endregion if (overLimit) { MsgBox.Show("匯出資料已經超過Excel的極限(65536筆)。\n超出的資料無法被匯出。\n\n請減少選取學生人數。"); } System.Diagnostics.Process.Start(path); } else { SmartSchool.Customization.PlugIn.Global.SetStatusBarMessage(_Title + "發生未預期錯誤。"); } }
void _bgWorker_DoWork(object sender, DoWorkEventArgs e) { _bgWorker.ReportProgress(1); // 取得部別、班別對照 ConfigData cd = new ConfigData(); Dictionary <string, List <ConfigDataItem> > cdDict = cd.GetConfigDataItemDict(); Dictionary <string, string> DepMappingDict = new Dictionary <string, string>(); Dictionary <string, string> ClsMappingDict = new Dictionary <string, string>(); Dictionary <string, string> DeptMappingDict = new Dictionary <string, string>(); Dictionary <string, string> ClassNoMappingDict = new Dictionary <string, string>(); Dictionary <string, string> ClassIDNameDict = new Dictionary <string, string>(); Dictionary <string, List <string> > StudTagNameDict = new Dictionary <string, List <string> >(); List <SHStudentTagRecord> SHStudentTagRecordList = SHStudentTag.SelectByStudentIDs(_StudentIDList); // 取得學期對照班級座號轉成大學繁星班代 Dictionary <string, string> StudentSHClassSeatNoDict = Utility.GetStudentClassCodeSeatNo(_StudentIDList, _SchoolYear, _Semester, true); // 取得學生科別名稱 Dictionary <string, string> StudeDeptNameDict = Utility.GetStudDeptNameDict(_StudentIDList, _SchoolYear, _Semester); // 取得學生類別 foreach (SHStudentTagRecord TRec in SHStudentTagRecordList) { if (!StudTagNameDict.ContainsKey(TRec.RefStudentID)) { StudTagNameDict.Add(TRec.RefStudentID, new List <string>()); } StudTagNameDict[TRec.RefStudentID].Add(TRec.FullName); } _bgWorker.ReportProgress(20); foreach (SHClassRecord rec in SHClass.SelectAll()) { ClassIDNameDict.Add(rec.ID, rec.Name); } // 部別對照 if (cdDict.ContainsKey("部別代碼")) { foreach (ConfigDataItem cdi in cdDict["部別代碼"]) { if (!DepMappingDict.ContainsKey(cdi.TargetName)) { DepMappingDict.Add(cdi.TargetName, cdi.Value); } } } // 班別對照 if (cdDict.ContainsKey("班別代碼")) { foreach (ConfigDataItem cdi in cdDict["班別代碼"]) { if (!ClsMappingDict.ContainsKey(cdi.TargetName)) { ClsMappingDict.Add(cdi.TargetName, cdi.Value); } } } // 科別對照 DeptMappingDict = Utility.GetDepartmetDict(); // 班級代碼對照 ClassNoMappingDict = Utility.GetLHClassCodeDict(); _bgWorker.ReportProgress(40); // 取得學生本資料 List <SHStudentRecord> StudentRecordList = SHStudent.SelectByIDs(_StudentIDList); List <StudentBaseRec> StudentBaseRecList = new List <StudentBaseRec>(); // 整理資料 foreach (SHStudentRecord studRec in StudentRecordList) { // 身分證號,出生日期,所屬學校代碼,科/班/學程別代碼,部別,班別,班級座號代碼 StudentBaseRec sbr = new StudentBaseRec(); sbr.IDNumber = studRec.IDNumber.ToUpper(); sbr.BirthDate = Utility.ConvertChDateString(studRec.Birthday); sbr.SchoolCode = _SchoolCode; // 科/班/學程別代碼 sbr.DCLCode = ""; if (StudeDeptNameDict.ContainsKey(studRec.ID)) { string name = StudeDeptNameDict[studRec.ID]; if (DeptMappingDict.ContainsKey(name)) { sbr.DCLCode = DeptMappingDict[name]; } } // 部別 sbr.DepCode = _DepCode; // 班別 sbr.ClCode = _ClassCode; if (StudTagNameDict.ContainsKey(studRec.ID)) { foreach (string str in StudTagNameDict[studRec.ID]) { if (DepMappingDict.ContainsKey(str)) { sbr.DepCode = DepMappingDict[str]; } if (ClsMappingDict.ContainsKey(str)) { sbr.ClCode = ClsMappingDict[str]; } } } // 班級座號代碼 sbr.ClassSeatCode = ""; if (StudentSHClassSeatNoDict.ContainsKey(studRec.ID)) { sbr.ClassSeatCode = StudentSHClassSeatNoDict[studRec.ID]; } else { //如果學年度學期和系統預設相同 if (K12.Data.School.DefaultSchoolYear == _SchoolYear.ToString() && K12.Data.School.DefaultSemester == _Semester.ToString()) { if (ClassIDNameDict.ContainsKey(studRec.RefClassID)) { string cName = ClassIDNameDict[studRec.RefClassID]; if (ClassNoMappingDict.ContainsKey(cName) && studRec.SeatNo.HasValue) { sbr.ClassSeatCode = ClassNoMappingDict[cName] + string.Format("{0:00}", studRec.SeatNo.Value); } } } } StudentBaseRecList.Add(sbr); } _bgWorker.ReportProgress(80); // 排序 班級座號代碼 StudentBaseRecList = (from data in StudentBaseRecList orderby data.ClassSeatCode ascending select data).ToList(); // 填值到 Excel _wb = new Workbook(new MemoryStream(Properties.Resources.學生資料名冊樣板_國教署主管學校_)); Worksheet wst1 = _wb.Worksheets["學生資料名冊封面"]; Worksheet wst2 = _wb.Worksheets["學生資料名冊"]; // 學校代碼,學年度,學期,名冊別 wst1.Cells[1, 0].PutValue(_SchoolCode); wst1.Cells[1, 1].PutValue(_SchoolYear); wst1.Cells[1, 2].PutValue(_Semester); wst1.Cells[1, 3].PutValue(_DocType); // 身分證號,出生日期,所屬學校代碼,科/班/學程別代碼,部別,班別,班級座號代碼 int rowIdx = 1; foreach (StudentBaseRec sbr in StudentBaseRecList) { wst2.Cells[rowIdx, 0].PutValue(sbr.IDNumber); wst2.Cells[rowIdx, 1].PutValue(sbr.BirthDate); wst2.Cells[rowIdx, 2].PutValue(sbr.SchoolCode); wst2.Cells[rowIdx, 3].PutValue(sbr.DCLCode); wst2.Cells[rowIdx, 4].PutValue(sbr.DepCode); wst2.Cells[rowIdx, 5].PutValue(sbr.ClCode); wst2.Cells[rowIdx, 6].PutValue(sbr.ClassSeatCode); rowIdx++; } _bgWorker.ReportProgress(100); }
void _bgWorker_DoWork(object sender, DoWorkEventArgs e) { _bgWorker.ReportProgress(1); // 取得部別、班別對照 ConfigData cd = new ConfigData(); Dictionary <string, List <ConfigDataItem> > cdDict = cd.GetConfigDataItemDict(); Dictionary <string, string> DepMappingDict = new Dictionary <string, string>(); Dictionary <string, string> ClsMappingDict = new Dictionary <string, string>(); Dictionary <string, string> DeptMappingDict = new Dictionary <string, string>(); Dictionary <string, string> ClassNoMappingDict = new Dictionary <string, string>(); Dictionary <string, string> ClassIDNameDict = new Dictionary <string, string>(); Dictionary <string, List <string> > StudTagNameDict = new Dictionary <string, List <string> >(); List <SHStudentTagRecord> SHStudentTagRecordList = SHStudentTag.SelectByStudentIDs(_StudentIDList); // 取得學生科別名稱 Dictionary <string, string> StudeDeptNameDict = Utility.GetStudDeptNameDict(_StudentIDList, _SchoolYear, _Semester); // 取得學生類別 foreach (SHStudentTagRecord TRec in SHStudentTagRecordList) { if (!StudTagNameDict.ContainsKey(TRec.RefStudentID)) { StudTagNameDict.Add(TRec.RefStudentID, new List <string>()); } StudTagNameDict[TRec.RefStudentID].Add(TRec.FullName); } _bgWorker.ReportProgress(20); foreach (SHClassRecord rec in SHClass.SelectAll()) { ClassIDNameDict.Add(rec.ID, rec.Name); } // 班級代碼對照 ClassNoMappingDict = Utility.GetLHClassCodeDict(); // 班別對照 if (cdDict.ContainsKey("班別代碼")) { foreach (ConfigDataItem cdi in cdDict["班別代碼"]) { if (!ClsMappingDict.ContainsKey(cdi.TargetName)) { ClsMappingDict.Add(cdi.TargetName, cdi.Value); } } } // 科別對照 DeptMappingDict = Utility.GetDepartmetDict(); // 取得學生基本資料 List <SHStudentRecord> StudentRecList = SHStudent.SelectByIDs(_StudentIDList); _bgWorker.ReportProgress(40); // 取得學期對照轉成大學繁星代碼 Dictionary <string, string> StudentSHClassCodDict = Utility.GetStudentClassCodeSeatNo(_StudentIDList, _SchoolYear, _Semester, false); // 取得學生定期成績資料 Dictionary <string, List <StudentSCETakeRec> > StudSCETakeDict = Utility.GetStudentSCETakeDict(_StudentIDList, _ExamID, _SchoolYear, _Semester); // 填入對應值 foreach (SHStudentRecord StudRec in StudentRecList) { if (StudSCETakeDict.ContainsKey(StudRec.ID)) { string IDNumber = StudRec.IDNumber.ToUpper(); string BirthDate = Utility.ConvertChDateString(StudRec.Birthday); // 科/班/學程別代碼 string DCLCode = "000"; if (StudeDeptNameDict.ContainsKey(StudRec.ID)) { string name = StudeDeptNameDict[StudRec.ID]; if (DeptMappingDict.ContainsKey(name)) { DCLCode = DeptMappingDict[name]; } } // 修課班別 string ClClassName = _ClassTypeCode; if (StudTagNameDict.ContainsKey(StudRec.ID)) { foreach (string str in StudTagNameDict[StudRec.ID]) { if (ClsMappingDict.ContainsKey(str)) { ClClassName = ClsMappingDict[str]; } } } // 修課班級 string ClassCode = "000"; if (StudentSHClassCodDict.ContainsKey(StudRec.ID)) { ClassCode = StudentSHClassCodDict[StudRec.ID]; } else { if (K12.Data.School.DefaultSchoolYear == _SchoolYear.ToString() && K12.Data.School.DefaultSemester == _Semester.ToString()) { if (ClassIDNameDict.ContainsKey(StudRec.RefClassID)) { string cName = ClassIDNameDict[StudRec.RefClassID]; if (ClassNoMappingDict.ContainsKey(cName)) { ClassCode = ClassNoMappingDict[cName]; } } } } foreach (StudentSCETakeRec rec in StudSCETakeDict[StudRec.ID]) { rec.IDNumber = IDNumber; rec.BirthDate = BirthDate; rec.ClassName = ClassCode; rec.ClClassName = ClClassName; rec.DCLCode = DCLCode; } } } _bgWorker.ReportProgress(70); List <StudentSCETakeRec> StudentSCETakeRecList = new List <StudentSCETakeRec>(); foreach (List <StudentSCETakeRec> recList in StudSCETakeDict.Values) { foreach (StudentSCETakeRec rec in recList) { StudentSCETakeRecList.Add(rec); } } // 排序 依身分證,科目代碼 StudentSCETakeRecList = (from data in StudentSCETakeRecList orderby data.IDNumber ascending, data.SubjectCode ascending select data).ToList(); // 填入Excel _wb = new Workbook(new MemoryStream(Properties.Resources.定期考查成績名冊樣板)); Worksheet wst1 = _wb.Worksheets["定期考查成績名冊封面"]; Worksheet wst2 = _wb.Worksheets["定期考查成績名冊"]; // 學校代碼 0,學年度 1,學期 2,段考別 3,名冊別 4 wst1.Cells[1, 0].PutValue(_SchoolCode); wst1.Cells[1, 1].PutValue(_SchoolYear); wst1.Cells[1, 2].PutValue(_Semester); wst1.Cells[1, 3].PutValue(_ExamNo); wst1.Cells[1, 4].PutValue(_DocType); // 身分證號 0,出生日期 1,科目代碼 2,科目學分 3,修課科/班/學程別代碼 4, //修課班級 5,修課班別 6,考查成績 7,狀態代碼 8 int rowIdx = 1; foreach (StudentSCETakeRec rec in StudentSCETakeRecList) { wst2.Cells[rowIdx, 0].PutValue(rec.IDNumber); wst2.Cells[rowIdx, 1].PutValue(rec.BirthDate); wst2.Cells[rowIdx, 2].PutValue(rec.SubjectCode); wst2.Cells[rowIdx, 3].PutValue(rec.SubjectCredit); wst2.Cells[rowIdx, 4].PutValue(rec.DCLCode); wst2.Cells[rowIdx, 5].PutValue(rec.ClassName); wst2.Cells[rowIdx, 6].PutValue(rec.ClClassName); wst2.Cells[rowIdx, 7].PutValue(rec.Score); wst2.Cells[rowIdx, 8].PutValue(rec.Status); rowIdx++; } _bgWorker.ReportProgress(100); }
private void _bgWorker_DoWork(object sender, DoWorkEventArgs e) { Document doc = new Document(); Document template = null; if (radioButton1.Checked == true) { //選擇預設範本時的動作 template = new Document(new MemoryStream(defalutTemplate)); } else if (radioButton2.Checked == true) { //選擇自訂範本時的動作 //School.Configuration.Remove(cd); //return; string str = cd["CustomizeTemplate"]; if (template == null) { try { template = (new Document(new MemoryStream(Convert.FromBase64String(str)))).Clone(); } catch (Exception ex) { throw new InvalidOperationException("尚未上傳自訂樣板"); //MsgBox.Show("尚未上傳自訂樣板"); //return; } //template = new Document(new MemoryStream(defalutTemplate)); } } else { MsgBox.Show(""); return; } //取得文號、字號、學年度學期取得 string No1 = textBoxX1.Text; string No2 = textBoxX2.Text; int schoolYear = int.Parse(K12.Data.School.DefaultSchoolYear); int semester = int.Parse(K12.Data.School.DefaultSemester); //取得學校名稱 string DSNSName = SHSchool.Data.SHSchoolInfo.ChineseName; string Principal = K12.Data.School.Configuration["學校資訊"].PreviousData.SelectSingleNode("ChancellorChineseName").InnerText; #region 取得選取學生 List <SHStudentRecord> studentAll = SHStudent.SelectByIDs(studentIds); List <SHUpdateRecordRecord> updateRecord = SHUpdateRecord.SelectByStudentIDs(studentIds); Dictionary <string, StudentObj> dic = new Dictionary <string, StudentObj>(); foreach (SHUpdateRecordRecord urr in updateRecord) { if (dic.ContainsKey(urr.StudentID)) { SHUpdateRecordRecord old = dic[urr.StudentID].URR; int newSchoolYear = urr.SchoolYear.HasValue ? urr.SchoolYear.Value : 0; int newSemester = urr.Semester.HasValue ? urr.Semester.Value : 0; int oldSchoolYear = old.SchoolYear.HasValue ? old.SchoolYear.Value : 0; int oldSemester = old.Semester.HasValue ? old.Semester.Value : 0; if (newSchoolYear > oldSchoolYear) { dic[urr.StudentID].URR = urr; } else if (newSchoolYear == oldSchoolYear) { if (newSemester > oldSemester) { dic[urr.StudentID].URR = urr; } } } if (updateCode.Contains(urr.UpdateCode) && !dic.ContainsKey(urr.StudentID)) { dic.Add(urr.StudentID, new StudentObj()); dic[urr.StudentID].URR = urr; } } foreach (SHStudentRecord sr in studentAll) { if (dic.ContainsKey(sr.ID)) { dic[sr.ID].Student = sr; } } #endregion Dictionary <string, object> merge = new Dictionary <string, object>(); string serverTime = GetServerTime(); foreach (StudentObj obj in dic.Values) { Document perPage = template.Clone(); merge.Clear(); merge.Add("起始時間", dateTimeInput1.Value.ToString("yyyy年MM月dd日")); merge.Add("訖末時間", dateTimeInput2.Value.ToString("yyyy年MM月dd日")); merge.Add("編字", No1); merge.Add("編號", No2); merge.Add("年級", schoolYear); merge.Add("學期", semester); merge.Add("學校名稱", DSNSName); merge.Add("校長姓名", Principal); merge.Add("列印日期", serverTime); merge.Add("學生姓名", obj.Student.Name); merge.Add("學號", obj.Student.StudentNumber); merge.Add("休學年級", obj.URR.GradeYear); merge.Add("休學學期", obj.URR.Semester); merge.Add("科系", obj.URR == null ? string.Empty : obj.URR.Department); merge.Add("休學事由", obj.URR == null ? string.Empty : obj.URR.UpdateDescription); perPage.MailMerge.Execute(merge.Keys.ToArray <string>(), merge.Values.ToArray <object>()); perPage.MailMerge.RemoveEmptyParagraphs = true; perPage.MailMerge.DeleteFields(); doc.Sections.Add(doc.ImportNode(perPage.Sections[0], true)); } doc.Sections.RemoveAt(0); e.Result = doc; }
void _BGWDisciplineDetail_DoWork(object sender, DoWorkEventArgs e) { string reportName = "學生獎勵明細"; #region 快取相關資料 //選擇的學生 List <SHStudentRecord> selectedStudents = SHStudent.SelectByIDs(K12.Presentation.NLDPanels.Student.SelectedSource); selectedStudents.Sort(new Comparison <SHStudentRecord>(CommonMethods.SHClassSeatNoComparer)); //紀錄所有學生ID List <string> allStudentID = new List <string>(); //每一位學生的獎勵明細 Dictionary <string, Dictionary <string, Dictionary <string, string> > > studentDisciplineDetail = new Dictionary <string, Dictionary <string, Dictionary <string, string> > >(); //每一位學生的獎勵累計資料 Dictionary <string, Dictionary <string, int> > studentDisciplineStatistics = new Dictionary <string, Dictionary <string, int> >(); //紀錄每一種獎勵在報表中的 column index Dictionary <string, int> columnTable = new Dictionary <string, int>(); //取得所有學生ID foreach (SHStudentRecord var in selectedStudents) { allStudentID.Add(var.ID); } //對照表 Dictionary <string, string> meritTable = new Dictionary <string, string>(); meritTable.Add("A", "大功"); meritTable.Add("B", "小功"); meritTable.Add("C", "嘉獎"); //初始化 string[] columnString = new string[] { "嘉獎", "小功", "大功", "事由", "備註" }; int i = 4; foreach (string s in columnString) { columnTable.Add(s, i++); } //產生 DSRequest,取得缺曠明細 DSResponse dsrsp; if (form.SelectDayOrSchoolYear) //依日期 { if (form.SetupTime) //依發生日期 { #region 依發生日期 DSXmlHelper helper = new DSXmlHelper("Request"); helper.AddElement("Field"); helper.AddElement("Field", "All"); helper.AddElement("Condition"); foreach (string var in allStudentID) { helper.AddElement("Condition", "RefStudentID", var); } helper.AddElement("Condition", "StartDate", form.StartDay); helper.AddElement("Condition", "EndDate", form.EndDay); helper.AddElement("Order"); helper.AddElement("Order", "OccurDate", "asc"); dsrsp = QueryDiscipline.GetDiscipline(new DSRequest(helper)); #endregion } else //依登錄日期 { #region 依登錄日期 DSXmlHelper helper = new DSXmlHelper("Request"); helper.AddElement("Field"); helper.AddElement("Field", "All"); helper.AddElement("Condition"); foreach (string var in allStudentID) { helper.AddElement("Condition", "RefStudentID", var); } helper.AddElement("Condition", "StartRegisterDate", form.StartDay); helper.AddElement("Condition", "EndRegisterDate", form.EndDay); helper.AddElement("Order"); helper.AddElement("Order", "OccurDate", "asc"); dsrsp = QueryDiscipline.GetDiscipline(new DSRequest(helper)); #endregion } } else //依學期 { if (form.checkBoxX1Bool) //全部學期列印 { #region 全部學期列印 DSXmlHelper helper = new DSXmlHelper("Request"); helper.AddElement("Field"); helper.AddElement("Field", "All"); helper.AddElement("Condition"); foreach (string var in allStudentID) { helper.AddElement("Condition", "RefStudentID", var); } helper.AddElement("Order"); helper.AddElement("Order", "OccurDate", "asc"); dsrsp = QueryDiscipline.GetDiscipline(new DSRequest(helper)); #endregion } else //指定學期列印 { #region 指定學期列印 DSXmlHelper helper = new DSXmlHelper("Request"); helper.AddElement("Field"); helper.AddElement("Field", "All"); helper.AddElement("Condition"); foreach (string var in allStudentID) { helper.AddElement("Condition", "RefStudentID", var); } helper.AddElement("Condition", "SchoolYear", form.SchoolYear); helper.AddElement("Condition", "Semester", form.Semester); helper.AddElement("Order"); helper.AddElement("Order", "OccurDate", "asc"); dsrsp = QueryDiscipline.GetDiscipline(new DSRequest(helper)); #endregion } } if (dsrsp == null) { MsgBox.Show("未取得獎勵資料"); return; } foreach (XmlElement var in dsrsp.GetContent().GetElements("Discipline")) { if (var.SelectSingleNode("MeritFlag").InnerText == "1") { string studentID = var.SelectSingleNode("RefStudentID").InnerText; string schoolYear = var.SelectSingleNode("SchoolYear").InnerText; string semester = var.SelectSingleNode("Semester").InnerText; string occurDate = DateTime.Parse(var.SelectSingleNode("OccurDate").InnerText).ToShortDateString(); string reason = var.SelectSingleNode("Reason").InnerText; string remark = var.SelectSingleNode("Remark").InnerText; //2019/12/31 - 新增 string disciplineID = var.GetAttribute("ID"); string sso = schoolYear + "_" + semester + "_" + occurDate + "_" + disciplineID; //初始化累計資料 if (!studentDisciplineStatistics.ContainsKey(studentID)) { studentDisciplineStatistics.Add(studentID, new Dictionary <string, int>()); } //每一位學生獎勵資料 if (!studentDisciplineDetail.ContainsKey(studentID)) { studentDisciplineDetail.Add(studentID, new Dictionary <string, Dictionary <string, string> >()); } if (!studentDisciplineDetail[studentID].ContainsKey(sso)) { studentDisciplineDetail[studentID].Add(sso, new Dictionary <string, string>()); } //加入事由 if (!studentDisciplineDetail[studentID][sso].ContainsKey("事由")) { studentDisciplineDetail[studentID][sso].Add("事由", reason); } //加入事由 if (!studentDisciplineDetail[studentID][sso].ContainsKey("備註")) { studentDisciplineDetail[studentID][sso].Add("備註", remark); } XmlElement discipline = (XmlElement)var.SelectSingleNode("Detail/Discipline/Merit"); foreach (XmlAttribute attr in discipline.Attributes) { if (meritTable.ContainsKey(attr.Name)) { string name = meritTable[attr.Name]; if (!studentDisciplineStatistics[studentID].ContainsKey(name)) { studentDisciplineStatistics[studentID].Add(name, 0); } int v; if (int.TryParse(attr.InnerText, out v)) { studentDisciplineStatistics[studentID][name] += v; } if (!studentDisciplineDetail[studentID][sso].ContainsKey(name)) { studentDisciplineDetail[studentID][sso].Add(name, attr.InnerText); } } } } } #endregion #region 產生範本 Workbook template = new Workbook(); template.Open(new MemoryStream(Properties.Resources.學生獎勵記錄明細), FileFormatType.Excel2003); Workbook prototype = new Workbook(); prototype.Copy(template); Worksheet ptws = prototype.Worksheets[0]; int startPage = 1; int pageNumber = 1; int columnNumber = 9; //合併標題列 ptws.Cells.CreateRange(0, 0, 1, columnNumber).Merge(); ptws.Cells.CreateRange(1, 0, 1, columnNumber).Merge(); Range ptHeader = ptws.Cells.CreateRange(0, 4, false); Range ptEachRow = ptws.Cells.CreateRange(4, 1, false); #endregion #region 產生報表 Workbook wb = new Workbook(); wb.Copy(prototype); Worksheet ws = wb.Worksheets[0]; int index = 0; int dataIndex = 0; int studentCount = 1; foreach (SHStudentRecord studentInfo in selectedStudents) { //回報進度 _BGWDisciplineDetail.ReportProgress((int)(((double)studentCount++ *100.0) / (double)selectedStudents.Count)); if (!studentDisciplineDetail.ContainsKey(studentInfo.ID)) { continue; } //如果不是第一頁,就在上一頁的資料列下邊加黑線 if (index != 0) { ws.Cells.CreateRange(index - 1, 0, 1, columnNumber).SetOutlineBorder(BorderType.BottomBorder, CellBorderType.Medium, Color.Black); } //複製 Header ws.Cells.CreateRange(index, 4, false).Copy(ptHeader); //填寫基本資料 ws.Cells[index, 0].PutValue(School.ChineseName + " 個人獎勵明細"); ws.Cells[index + 1, 0].PutValue("班級:" + ((studentInfo.Class == null) ? " " : studentInfo.Class.Name) + " 座號:" + ((studentInfo.SeatNo == null) ? " " : studentInfo.SeatNo.ToString()) + " 姓名:" + studentInfo.Name + " 學號:" + studentInfo.StudentNumber); dataIndex = index + 4; int recordCount = 0; Dictionary <string, Dictionary <string, string> > disciplineDetail = studentDisciplineDetail[studentInfo.ID]; foreach (string sso in disciplineDetail.Keys) { string[] ssoSplit = sso.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries); //複製每一個 row ws.Cells.CreateRange(dataIndex, 1, false).Copy(ptEachRow); //填寫學生獎勵資料 ws.Cells[dataIndex, 0].PutValue(ssoSplit[0]); ws.Cells[dataIndex, 1].PutValue(ssoSplit[1]); ws.Cells[dataIndex, 2].PutValue(ssoSplit[2]); ws.Cells[dataIndex, 3].PutValue(CommonMethods.GetChineseDayOfWeek(DateTime.Parse(ssoSplit[2]))); Dictionary <string, string> record = disciplineDetail[sso]; foreach (string name in record.Keys) { if (meritTable.ContainsValue(name)) { int v; if (int.TryParse(record[name], out v)) { if (v > 0) { ws.Cells[dataIndex, columnTable[name]].PutValue(record[name]); } } } else { if (columnTable.ContainsKey(name)) { ws.Cells[dataIndex, columnTable[name]].PutValue(record[name]); } } } dataIndex++; recordCount++; } //獎懲統計資訊 Range disciplineStatisticsRange = ws.Cells.CreateRange(dataIndex, 0, 1, columnNumber); disciplineStatisticsRange.Copy(ptEachRow); disciplineStatisticsRange.Merge(); disciplineStatisticsRange.SetOutlineBorder(BorderType.TopBorder, CellBorderType.Double, Color.Black); disciplineStatisticsRange.SetOutlineBorder(BorderType.BottomBorder, CellBorderType.Double, Color.Black); disciplineStatisticsRange.RowHeight = 20.0; ws.Cells[dataIndex, 0].Style.HorizontalAlignment = TextAlignmentType.Center; ws.Cells[dataIndex, 0].Style.VerticalAlignment = TextAlignmentType.Center; ws.Cells[dataIndex, 0].Style.Font.Size = 10; ws.Cells[dataIndex, 0].PutValue("獎勵總計"); dataIndex++; //獎懲統計內容 ws.Cells.CreateRange(dataIndex, 0, 1, columnNumber).Copy(ptEachRow); ws.Cells.CreateRange(dataIndex, 0, 1, columnNumber).RowHeight = 27.0; ws.Cells.CreateRange(dataIndex, 0, 1, columnNumber).Merge(); ws.Cells[dataIndex, 0].Style.HorizontalAlignment = TextAlignmentType.Center; ws.Cells[dataIndex, 0].Style.VerticalAlignment = TextAlignmentType.Center; ws.Cells[dataIndex, 0].Style.Font.Size = 10; ws.Cells[dataIndex, 0].Style.ShrinkToFit = true; StringBuilder text = new StringBuilder(""); Dictionary <string, int> disciplineStatistics = studentDisciplineStatistics[studentInfo.ID]; foreach (string type in disciplineStatistics.Keys) { if (disciplineStatistics[type] > 0) { if (text.ToString() != "") { text.Append(" "); } text.Append(type + ":" + disciplineStatistics[type]); } } ws.Cells[dataIndex, 0].PutValue(text.ToString()); dataIndex++; //資料列上邊加上黑線 ws.Cells.CreateRange(index + 3, 0, 1, columnNumber).SetOutlineBorder(BorderType.BottomBorder, CellBorderType.Medium, Color.Black); //表格最右邊加上黑線 ws.Cells.CreateRange(index + 2, columnNumber - 1, recordCount + 4, 1).SetOutlineBorder(BorderType.RightBorder, CellBorderType.Medium, Color.Black); index = dataIndex; //設定分頁 if (pageNumber < 500) { ws.HPageBreaks.Add(index, columnNumber); pageNumber++; } else { ws.Name = startPage + " ~ " + (pageNumber + startPage - 1); ws = wb.Worksheets[wb.Worksheets.Add()]; ws.Copy(prototype.Worksheets[0]); startPage += pageNumber; pageNumber = 1; index = 0; } } if (dataIndex > 0) { //最後一頁的資料列下邊加上黑線 ws.Cells.CreateRange(dataIndex - 1, 0, 1, columnNumber).SetOutlineBorder(BorderType.BottomBorder, CellBorderType.Medium, Color.Black); ws.Name = startPage + " ~ " + (pageNumber + startPage - 2); } else { wb = new Workbook(); } #endregion string path = Path.Combine(Application.StartupPath, "Reports"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = Path.Combine(path, reportName + ".xlt"); e.Result = new object[] { reportName, path, wb }; }
private void SearchDateRange() { #region 日期選擇 DateTime start = dateTimeInput1.Value; DateTime end = dateTimeInput2.Value; dataGridView.Rows.Clear(); TimeSpan ts = dateTimeInput2.Value - dateTimeInput1.Value; if (ts.Days > 1500) { FISCA.Presentation.Controls.MsgBox.Show("您選取了" + ts.Days.ToString() + "天\n由於選取日期區間過長,請重新設定日期!"); _currentStartDate = dateTimeInput1.Value = DateTime.Today; _currentEndDate = dateTimeInput2.Value = DateTime.Today; return; } List <SHStudentRecord> CatchStudentList = SHStudent.SelectByIDs(_studentList); CatchStudentList = SortClassIndex.SHSchoolData_SHStudentRecord(CatchStudentList); bool ColorTrue = true; foreach (SHStudentRecord each in CatchStudentList) { DateTime date = start; if (ColorTrue) { ColorTrue = false; } else { ColorTrue = true; } while (date.CompareTo(end) <= 0) { if (!nowWeekDay.Contains(date.DayOfWeek)) //這裡 { date = date.AddDays(1); continue; } string dateValue = date.ToShortDateString(); DataGridViewRow row = new DataGridViewRow(); row.CreateCells(dataGridView); if (ColorTrue) { SetDataGridViewColor(row, ColorTrue); } else { SetDataGridViewColor(row, ColorTrue); } RowTag tag = new RowTag(); tag.Date = date; tag.IsNew = true; row.Tag = tag; //RowTag row.Cells[0].Tag = each.ID; //系統編號 row.Cells[ColumnIndex["班級"]].Value = each.Class != null ? each.Class.Name : ""; row.Cells[ColumnIndex["座號"]].Value = each.SeatNo.HasValue ? each.SeatNo.Value.ToString() : ""; row.Cells[ColumnIndex["姓名"]].Value = each.Name; row.Cells[ColumnIndex["學號"]].Value = each.StudentNumber; row.Cells[ColumnIndex["日期"]].Value = dateValue; row.Cells[ColumnIndex["星期"]].Value = GetDayOfWeekInChinese(date.DayOfWeek); _semesterProvider.SetDate(date); row.Cells[ColumnIndex["學年度"]].Value = _semesterProvider.SchoolYear.ToString(); row.Cells[ColumnIndex["學期"]].Value = _semesterProvider.Semester.ToString(); date = date.AddDays(1); dataGridView.Rows.Add(row); } } #endregion }
public override void InitializeExport(SmartSchool.API.PlugIn.Export.ExportWizard wizard) { //取得文字評量代碼表清單 List <string> faceList = GetConfig.GetWordCommentList(); //加入欲匯出之欄位資料 wizard.ExportableFields.AddRange("學年度", "學期"); foreach (string each in faceList) { wizard.ExportableFields.Add(each); } wizard.ExportPackage += delegate(object sender, SmartSchool.API.PlugIn.Export.ExportPackageEventArgs e) { //取得學生清單 List <SHStudentRecord> students = SHStudent.SelectByIDs(e.List); //取得學生相關文字評量記錄 Dictionary <string, List <SHMoralScoreRecord> > DicMoralScore = GetMoralScore(e.List); students.Sort(SortStudent); //整理填入資料 foreach (SHStudentRecord stud in students) //每一位學生 { if (DicMoralScore.ContainsKey(stud.ID)) { foreach (SHMoralScoreRecord MScore in DicMoralScore[stud.ID]) //每一筆資料 { //取得文字評量內容的Dictionary物件,可加快比對速度 Dictionary <string, string> studTextScore = GetTextScore(MScore); RowData row = new RowData(); row.ID = stud.ID; //對於每一個要匯出的欄位 foreach (string field in e.ExportFields) { if (wizard.ExportableFields.Contains(field)) { string value = ""; switch (field) { case "學年度": value = MScore.SchoolYear.ToString(); break; case "學期": value = MScore.Semester.ToString(); break; default: value = findTextScore(studTextScore, field); //取得文字評量 break; } row.Add(field, value); } } e.Items.Add(row); } } } }; }
void _bgWorker_DoWork(object sender, DoWorkEventArgs e) { _bgWorker.ReportProgress(1); // 取得部別、班別對照 ConfigData cd = new ConfigData(); Dictionary <string, List <ConfigDataItem> > cdDict = cd.GetConfigDataItemDict(); Dictionary <string, string> DepMappingDict = new Dictionary <string, string>(); Dictionary <string, string> ClsMappingDict = new Dictionary <string, string>(); Dictionary <string, string> DeptMappingDict = new Dictionary <string, string>(); Dictionary <string, string> ClassNoMappingDict = new Dictionary <string, string>(); Dictionary <string, string> ClassIDNameDict = new Dictionary <string, string>(); Dictionary <string, List <string> > StudTagNameDict = new Dictionary <string, List <string> >(); List <SHStudentTagRecord> SHStudentTagRecordList = SHStudentTag.SelectByStudentIDs(_StudentIDList); // 取得學期對照班級座號轉成大學繁星班代 Dictionary <string, string> StudentSHClassSeatNoDict = Utility.GetStudentClassCodeSeatNo(_StudentIDList, _SchoolYear, _Semester, true); // 取得學生科別名稱 Dictionary <string, string> StudeDeptNameDict = Utility.GetStudDeptNameDict(_StudentIDList, _SchoolYear, _Semester); // 取得學生異動資料 List <SHUpdateRecordRecord> SHUpdateRecordRecordList = SHUpdateRecord.SelectByStudentIDs(_StudentIDList); Dictionary <string, List <SHUpdateRecordRecord> > SHUpdateRecordRecordDict = new Dictionary <string, List <SHUpdateRecordRecord> >(); // 沒有核准日期文號不排入,並符合所選的學年度學期 foreach (SHUpdateRecordRecord urRec in SHUpdateRecordRecordList) { if (string.IsNullOrWhiteSpace(urRec.ADDate) || string.IsNullOrWhiteSpace(urRec.ADNumber)) { continue; } if (urRec.SchoolYear.HasValue && urRec.Semester.HasValue) { if (urRec.SchoolYear <= _SchoolYear && urRec.Semester <= _Semester) { if (!SHUpdateRecordRecordDict.ContainsKey(urRec.StudentID)) { SHUpdateRecordRecordDict.Add(urRec.StudentID, new List <SHUpdateRecordRecord>()); } SHUpdateRecordRecordDict[urRec.StudentID].Add(urRec); } } } // 取得學生類別 foreach (SHStudentTagRecord TRec in SHStudentTagRecordList) { if (!StudTagNameDict.ContainsKey(TRec.RefStudentID)) { StudTagNameDict.Add(TRec.RefStudentID, new List <string>()); } StudTagNameDict[TRec.RefStudentID].Add(TRec.FullName); } _bgWorker.ReportProgress(20); foreach (SHClassRecord rec in SHClass.SelectAll()) { ClassIDNameDict.Add(rec.ID, rec.Name); } // 部別對照 if (cdDict.ContainsKey("部別代碼")) { foreach (ConfigDataItem cdi in cdDict["部別代碼"]) { if (!DepMappingDict.ContainsKey(cdi.TargetName)) { DepMappingDict.Add(cdi.TargetName, cdi.Value); } } } // 班別對照 if (cdDict.ContainsKey("班別代碼")) { foreach (ConfigDataItem cdi in cdDict["班別代碼"]) { if (!ClsMappingDict.ContainsKey(cdi.TargetName)) { ClsMappingDict.Add(cdi.TargetName, cdi.Value); } } } // 科別對照 DeptMappingDict = Utility.GetDepartmetDict(); // 班級代碼對照 ClassNoMappingDict = Utility.GetLHClassCodeDict(); _bgWorker.ReportProgress(40); // 取得學生本資料 List <SHStudentRecord> StudentRecordList = SHStudent.SelectByIDs(_StudentIDList); List <StudentBaseRec> StudentBaseRecList = new List <StudentBaseRec>(); // 整理資料 foreach (SHStudentRecord studRec in StudentRecordList) { // 身分證號,出生日期,所屬學校代碼,科/班/學程別代碼,部別,班別,班級座號代碼 StudentBaseRec sbr = new StudentBaseRec(); sbr.StudentNumber = studRec.StudentNumber; sbr.IDNumber = studRec.IDNumber.ToUpper(); sbr.BirthDate = Utility.ConvertChDateString(studRec.Birthday); sbr.SchoolCode = _SchoolCode; sbr.Name = studRec.Name; if (studRec.Gender == "男") { sbr.GenderCode = "1"; } if (studRec.Gender == "女") { sbr.GenderCode = "2"; } // 科/班/學程別代碼 sbr.DCLCode = ""; if (StudeDeptNameDict.ContainsKey(studRec.ID)) { string name = StudeDeptNameDict[studRec.ID]; if (DeptMappingDict.ContainsKey(name)) { sbr.DCLCode = DeptMappingDict[name]; } } // 部別 sbr.DepCode = _DepCode; // 班別 sbr.ClCode = _ClassCode; if (StudTagNameDict.ContainsKey(studRec.ID)) { foreach (string str in StudTagNameDict[studRec.ID]) { if (DepMappingDict.ContainsKey(str)) { sbr.DepCode = DepMappingDict[str]; } if (ClsMappingDict.ContainsKey(str)) { sbr.ClCode = ClsMappingDict[str]; } } } // 班級座號代碼 sbr.ClassSeatCode = ""; if (StudentSHClassSeatNoDict.ContainsKey(studRec.ID)) { sbr.ClassSeatCode = StudentSHClassSeatNoDict[studRec.ID]; if (sbr.ClassSeatCode.Length == 5) { sbr.ClassCode = sbr.ClassSeatCode.Substring(0, 3); } } else { //如果學年度學期和系統預設相同 if (K12.Data.School.DefaultSchoolYear == _SchoolYear.ToString() && K12.Data.School.DefaultSemester == _Semester.ToString()) { if (ClassIDNameDict.ContainsKey(studRec.RefClassID)) { string cName = ClassIDNameDict[studRec.RefClassID]; if (ClassNoMappingDict.ContainsKey(cName) && studRec.SeatNo.HasValue) { sbr.ClassSeatCode = ClassNoMappingDict[cName] + string.Format("{0:00}", studRec.SeatNo.Value); sbr.ClassCode = ClassNoMappingDict[cName]; } } } } // 處理異動相關 if (SHUpdateRecordRecordDict.ContainsKey(studRec.ID)) { // 排序 List <SHUpdateRecordRecord> UrDataList = (from data in SHUpdateRecordRecordDict[studRec.ID] orderby DateTime.Parse(data.ADDate) descending, int.Parse(data.ID) descending select data).ToList(); if (UrDataList.Count > 0) { SHUpdateRecordRecord rec = UrDataList[0]; sbr.PermrecCode = rec.UpdateCode; DateTime dt = DateTime.Parse(rec.UpdateDate); sbr.PermrecDate = Utility.ConvertChDateString(dt); sbr.OrBirthDate = "-1"; sbr.OrIDNumber = "-1"; sbr.Remak1 = rec.IDNumberComment; sbr.SpCode = rec.SpecialStatus; } foreach (SHUpdateRecordRecord rec in UrDataList) { // 再次檢查身分證與生日是否有差異 int iUcode = int.Parse(rec.UpdateCode); if (iUcode > 400 && iUcode < 411) { if (rec.IDNumber.ToUpper() != studRec.IDNumber.ToUpper()) { sbr.OrIDNumber = rec.IDNumber.ToUpper(); } if (studRec.Birthday.HasValue) { if (studRec.Birthday.Value.ToShortDateString() != rec.Birthdate) { DateTime dto = DateTime.Parse(rec.Birthdate); sbr.OrBirthDate = Utility.ConvertChDateString(dto); } } } } } StudentBaseRecList.Add(sbr); } _bgWorker.ReportProgress(80); // 排序 班級座號代碼 StudentBaseRecList = (from data in StudentBaseRecList orderby data.ClassSeatCode ascending select data).ToList(); // 統計人數 Dictionary <string, StudentBaseRecCount> StudentBaseRecCountDict = new Dictionary <string, StudentBaseRecCount>(); foreach (StudentBaseRec rec in StudentBaseRecList) { string key = rec.ClCode + rec.DCLCode + rec.DepCode + rec.ClassCode; if (!StudentBaseRecCountDict.ContainsKey(key)) { StudentBaseRecCount sbrc = new StudentBaseRecCount(); sbrc.ClassCode = rec.ClassCode; sbrc.ClCode = rec.ClCode; sbrc.DCLCode = rec.DCLCode; sbrc.DepCode = rec.DepCode; sbrc.DocType = _DocType; sbrc.SchoolCode = _SchoolCode; sbrc.SchoolYear = _SchoolYear; sbrc.Semester = _Semester; sbrc.StudentCount = 0; StudentBaseRecCountDict.Add(key, sbrc); } StudentBaseRecCountDict[key].StudentCount++; } List <StudentBaseRecCount> StudentBaseRecCountList = new List <StudentBaseRecCount>(); foreach (string Key in StudentBaseRecCountDict.Keys) { StudentBaseRecCountList.Add(StudentBaseRecCountDict[Key]); } // 排序,依班級代碼 StudentBaseRecCountList = (from data in StudentBaseRecCountList orderby data.ClassCode ascending select data).ToList(); // 填值到 Excel _wb = new Workbook(new MemoryStream(Properties.Resources.學生資料名冊樣板_非國教署主管學校_)); Worksheet wst1 = _wb.Worksheets["學生資料名冊封面"]; Worksheet wst2 = _wb.Worksheets["學生資料名冊"]; int rowIdx = 1; foreach (StudentBaseRecCount sbrc in StudentBaseRecCountList) { //學校代碼 0,學年度 1,學期 2,名冊別 3,科/班/學程別代碼 4,年級班級代碼 5,部別 6,班別 7,班級人數 8 wst1.Cells[rowIdx, 0].PutValue(sbrc.SchoolCode); wst1.Cells[rowIdx, 1].PutValue(sbrc.SchoolYear); wst1.Cells[rowIdx, 2].PutValue(sbrc.Semester); wst1.Cells[rowIdx, 3].PutValue(sbrc.DocType); wst1.Cells[rowIdx, 4].PutValue(sbrc.DCLCode); wst1.Cells[rowIdx, 5].PutValue(sbrc.ClassCode); wst1.Cells[rowIdx, 6].PutValue(sbrc.DepCode); wst1.Cells[rowIdx, 7].PutValue(sbrc.ClCode); wst1.Cells[rowIdx, 8].PutValue(sbrc.StudentCount); rowIdx++; } rowIdx = 1; foreach (StudentBaseRec sbr in StudentBaseRecList) { // 學號 0,身分證號 1,註1 2,姓名 3,性別代碼 4,出生日期 5,所屬學校代碼 6,科/班/學程別代碼 7,部別 8, //班別 9,班級座號代碼 10,特殊身分代碼 11,原身分證號 12,原出生日期 13,學籍狀態代碼 14,學籍狀態生效日期 15 wst2.Cells[rowIdx, 0].PutValue(sbr.StudentNumber); wst2.Cells[rowIdx, 1].PutValue(sbr.IDNumber); wst2.Cells[rowIdx, 2].PutValue(sbr.Remak1); wst2.Cells[rowIdx, 3].PutValue(sbr.Name); wst2.Cells[rowIdx, 4].PutValue(sbr.GenderCode); wst2.Cells[rowIdx, 5].PutValue(sbr.BirthDate); wst2.Cells[rowIdx, 6].PutValue(sbr.SchoolCode); wst2.Cells[rowIdx, 7].PutValue(sbr.DCLCode); wst2.Cells[rowIdx, 8].PutValue(sbr.DepCode); wst2.Cells[rowIdx, 9].PutValue(sbr.ClCode); wst2.Cells[rowIdx, 10].PutValue(sbr.ClassSeatCode); wst2.Cells[rowIdx, 11].PutValue(sbr.SpCode); wst2.Cells[rowIdx, 12].PutValue(sbr.OrIDNumber); wst2.Cells[rowIdx, 13].PutValue(sbr.OrBirthDate); wst2.Cells[rowIdx, 14].PutValue(sbr.PermrecCode); wst2.Cells[rowIdx, 15].PutValue(sbr.PermrecDate); rowIdx++; } _bgWorker.ReportProgress(100); }
public override void InitializeImport(SmartSchool.API.PlugIn.Import.ImportWizard wizard) { //學生資訊 Dictionary <string, SHStudentRecord> students = new Dictionary <string, SHStudentRecord>(); //學生修課資訊 studentID -> List:SCAttendRecord Dictionary <string, List <SHSCAttendRecord> > scattends = new Dictionary <string, List <SHSCAttendRecord> >(); //學生修習的課程 courseID -> CourseRecord Dictionary <string, SHCourseRecord> courses = new Dictionary <string, SHCourseRecord>(); //所有課程(依學年度學期分開) schoolYear_semester -> (courseName -> CourseRecord) Dictionary <string, Dictionary <string, SHCourseRecord> > allcourses = new Dictionary <string, Dictionary <string, SHCourseRecord> >(); //studentID_schoolYear_semester -> List:courseName Dictionary <string, List <string> > semesterCourseName = new Dictionary <string, List <string> >(); //準備加入修課的資料 studentID -> (schoolYear_semester_courseName -> RowData) Dictionary <string, Dictionary <string, RowData> > prepareAttends = new Dictionary <string, Dictionary <string, RowData> >(); wizard.PackageLimit = 3000; wizard.ImportableFields.Add("課程系統編號"); wizard.ImportableFields.AddRange("學年度", "學期"); wizard.ImportableFields.Add("課程名稱"); wizard.ImportableFields.AddRange("班級", "座號"); wizard.RequiredFields.AddRange("學年度", "學期"); wizard.RequiredFields.Add("課程名稱"); wizard.ValidateStart += delegate(object sender, SmartSchool.API.PlugIn.Import.ValidateStartEventArgs e) { #region 取得學生資訊 foreach (SHStudentRecord stu in SHStudent.SelectByIDs(e.List)) { if (!students.ContainsKey(stu.ID)) { students.Add(stu.ID, stu); } } #endregion #region 取得修課記錄 MultiThreadWorker <string> loader1 = new MultiThreadWorker <string>(); loader1.MaxThreads = 3; loader1.PackageSize = 250; loader1.PackageWorker += delegate(object sender1, PackageWorkEventArgs <string> e1) { foreach (SHSCAttendRecord record in SHSCAttend.SelectByStudentIDAndCourseID(e1.List, new string[] { })) { if (!scattends.ContainsKey(record.RefStudentID)) { scattends.Add(record.RefStudentID, new List <SHSCAttendRecord>()); } scattends[record.RefStudentID].Add(record); if (!courses.ContainsKey(record.RefCourseID)) { courses.Add(record.RefCourseID, null); } } }; loader1.Run(e.List); #endregion #region 取得課程資訊 MultiThreadWorker <string> loader2 = new MultiThreadWorker <string>(); loader2.MaxThreads = 3; loader2.PackageSize = 250; loader2.PackageWorker += delegate(object sender2, PackageWorkEventArgs <string> e2) { foreach (SHCourseRecord record in SHCourse.SelectByIDs(new List <string>(e2.List))) { if (courses.ContainsKey(record.ID)) { courses[record.ID] = record; } } }; loader2.Run(courses.Keys); foreach (SHCourseRecord course in SHCourse.SelectAll()) { string key = course.SchoolYear + "_" + course.Semester; if (!allcourses.ContainsKey(key)) { allcourses.Add(key, new Dictionary <string, SHCourseRecord>()); } if (!allcourses[key].ContainsKey(course.Name)) { allcourses[key].Add(course.Name, course); } } #endregion }; wizard.ValidateRow += delegate(object sender, SmartSchool.API.PlugIn.Import.ValidateRowEventArgs e) { int i; #region 檢查學生是否存在 SHStudentRecord student = null; if (students.ContainsKey(e.Data.ID)) { student = students[e.Data.ID]; } else { e.ErrorMessage = "壓根就沒有這個學生" + e.Data.ID; return; } #endregion #region 驗證各個欄位格式 bool inputFormatPass = true; foreach (string field in e.SelectFields) { string value = e.Data[field]; switch (field) { default: break; case "學年度": case "學期": if (value == "" || !int.TryParse(value, out i)) { inputFormatPass &= false; e.ErrorFields.Add(field, "必須填入整數"); } break; case "課程名稱": if (value == "") { inputFormatPass &= false; e.ErrorFields.Add(field, "必須填入課程名稱"); } break; case "班級": if (value == "") { } break; case "座號": if (value != "" && !int.TryParse(value, out i)) { inputFormatPass &= false; e.ErrorFields.Add(field, "必須填入空白或整數"); } break; } } #endregion //輸入格式正確才會針對情節做檢驗 #region 驗證各種情節 if (inputFormatPass) { string errorMessage = ""; string sy = e.Data["學年度"]; string se = e.Data["學期"]; string courseName = e.Data["課程名稱"]; string key = e.Data.ID + "_" + sy + "_" + se; string semsKey = sy + "_" + se; //int schoolyear = Framework.Int.ParseInt(sy); //int semester = Framework.Int.ParseInt(se); #region 一個學年度學期不能有重覆的課程名稱 if (!semesterCourseName.ContainsKey(key)) { semesterCourseName.Add(key, new List <string>()); } if (semesterCourseName[key].Contains(courseName)) { errorMessage += (errorMessage == "" ? "" : "\n") + " 同一學年度學期不允許修習多筆相同名稱的課程"; } else { semesterCourseName[key].Add(courseName); } #endregion #region 檢查課程是否存在系統中 bool noCourse = false; if (!allcourses.ContainsKey(semsKey)) { noCourse = true; errorMessage += (errorMessage == "" ? "" : "\n") + " 系統中找不到該課程"; } else if (!allcourses[semsKey].ContainsKey(courseName)) { noCourse = true; errorMessage += (errorMessage == "" ? "" : "\n") + " 系統中找不到該課程"; } else { } #endregion #region 檢查學生是否有修此課程 bool attended = false; if (scattends.ContainsKey(e.Data.ID)) { foreach (SHSCAttendRecord record in scattends[e.Data.ID]) { if (courses[record.RefCourseID].Name == courseName && "" + courses[record.RefCourseID].SchoolYear == sy && "" + courses[record.RefCourseID].Semester == se) { attended = true; } } } else //學生沒修半堂課 { } if (!attended && !noCourse) { if (!e.WarningFields.ContainsKey("無修課記錄")) { e.WarningFields.Add("無修課記錄", "學生在此學期並無修習此課程,將會新增修課記錄"); } if (!prepareAttends.ContainsKey(e.Data.ID)) { prepareAttends.Add(e.Data.ID, new Dictionary <string, RowData>()); } if (!prepareAttends[e.Data.ID].ContainsKey(semsKey + "_" + courseName)) { prepareAttends[e.Data.ID].Add(semsKey + "_" + courseName, e.Data); } } #endregion e.ErrorMessage = errorMessage; } #endregion }; wizard.ImportPackage += delegate(object sender, SmartSchool.API.PlugIn.Import.ImportPackageEventArgs e) { Dictionary <string, List <RowData> > id_Rows = new Dictionary <string, List <RowData> >(); #region 分包裝 foreach (RowData data in e.Items) { if (!id_Rows.ContainsKey(data.ID)) { id_Rows.Add(data.ID, new List <RowData>()); } id_Rows[data.ID].Add(data); } #endregion List <SHSCAttendRecord> insertList = new List <SHSCAttendRecord>(); List <SHSCAttendRecord> updateList = new List <SHSCAttendRecord>(); //交叉比對各學生資料 #region 交叉比對各學生資料 foreach (string id in id_Rows.Keys) { SHStudentRecord studentRec = students[id]; #region 處理要新增的修課記錄 if (prepareAttends.ContainsKey(id)) { foreach (RowData data in prepareAttends[id].Values) { string sy = data["學年度"]; string se = data["學期"]; string semsKey = sy + "_" + se; string courseName = data["課程名稱"]; if (allcourses.ContainsKey(semsKey) && allcourses[semsKey].ContainsKey(courseName)) { SHSCAttendRecord record = new SHSCAttendRecord(); record.RefStudentID = id; record.RefCourseID = allcourses[semsKey][courseName].ID; insertList.Add(record); } } } #endregion } try { if (updateList.Count > 0) { #region 分批次兩路上傳 List <List <SHSCAttendRecord> > updatePackages = new List <List <SHSCAttendRecord> >(); List <List <SHSCAttendRecord> > updatePackages2 = new List <List <SHSCAttendRecord> >(); { List <SHSCAttendRecord> package = null; int count = 0; foreach (SHSCAttendRecord var in updateList) { if (count == 0) { package = new List <SHSCAttendRecord>(30); count = 30; if ((updatePackages.Count & 1) == 0) { updatePackages.Add(package); } else { updatePackages2.Add(package); } } package.Add(var); count--; } } Thread threadUpdateSemesterSubjectScore = new Thread(new ParameterizedThreadStart(Update)); threadUpdateSemesterSubjectScore.IsBackground = true; threadUpdateSemesterSubjectScore.Start(updatePackages); Thread threadUpdateSemesterSubjectScore2 = new Thread(new ParameterizedThreadStart(Update)); threadUpdateSemesterSubjectScore2.IsBackground = true; threadUpdateSemesterSubjectScore2.Start(updatePackages2); threadUpdateSemesterSubjectScore.Join(); threadUpdateSemesterSubjectScore2.Join(); #endregion } } catch (Exception ex) { } if (insertList.Count > 0) { #region 分批次兩路上傳 List <List <SHSCAttendRecord> > insertPackages = new List <List <SHSCAttendRecord> >(); List <List <SHSCAttendRecord> > insertPackages2 = new List <List <SHSCAttendRecord> >(); { List <SHSCAttendRecord> package = null; int count = 0; foreach (SHSCAttendRecord var in insertList) { if (count == 0) { package = new List <SHSCAttendRecord>(30); count = 30; if ((insertPackages.Count & 1) == 0) { insertPackages.Add(package); } else { insertPackages2.Add(package); } } package.Add(var); count--; } } Thread threadInsertSemesterSubjectScore = new Thread(new ParameterizedThreadStart(Insert)); threadInsertSemesterSubjectScore.IsBackground = true; threadInsertSemesterSubjectScore.Start(insertPackages); Thread threadInsertSemesterSubjectScore2 = new Thread(new ParameterizedThreadStart(Insert)); threadInsertSemesterSubjectScore2.IsBackground = true; threadInsertSemesterSubjectScore2.Start(insertPackages2); threadInsertSemesterSubjectScore.Join(); threadInsertSemesterSubjectScore2.Join(); #endregion } ApplicationLog.Log("成績系統.匯入匯出", "匯入課程修課學生", "總共匯入" + (insertList.Count + updateList.Count) + "筆課程修課學生。"); #endregion }; }
public override void InitializeImport(SmartSchool.API.PlugIn.Import.ImportWizard wizard) { // 取得學生資料 Dictionary <string, SHStudentRecord> Students = new Dictionary <string, SHStudentRecord>(); // 取得異動資料 Dictionary <string, List <SHUpdateRecordRecord> > UpdateRecs = new Dictionary <string, List <SHUpdateRecordRecord> >(); wizard.PackageLimit = 3000; wizard.ImportableFields.AddRange("班別", "特殊身份代碼", "異動科別", "年級", "異動學號", "異動姓名", "身分證號", "註1", "異動代碼", "異動日期", "原因及事項", "新學號", "更正後資料", "舊班別", "舊科別代碼", "備查日期", "備查文號", "核准日期", "核准文號", "備註"); wizard.RequiredFields.AddRange("異動代碼", "異動日期"); wizard.ValidateStart += delegate(object sender, SmartSchool.API.PlugIn.Import.ValidateStartEventArgs e) { Students.Clear(); UpdateRecs.Clear(); // 取得學生資料 foreach (SHStudentRecord studRec in SHStudent.SelectByIDs(e.List)) { if (!Students.ContainsKey(studRec.ID)) { Students.Add(studRec.ID, studRec); } } foreach (string str in Students.Keys) { List <SHUpdateRecordRecord> UpdRecList = new List <SHUpdateRecordRecord>(); UpdateRecs.Add(str, UpdRecList); } // 取得異動 MultiThreadWorker <string> loader1 = new MultiThreadWorker <string>(); loader1.MaxThreads = 3; loader1.PackageSize = 250; loader1.PackageWorker += delegate(object sender1, PackageWorkEventArgs <string> e1) { foreach (SHUpdateRecordRecord UpdRec in SHUpdateRecord.SelectByStudentIDs(e.List)) { // 過濾非符合標準的異動(目前是學籍) if (!_UpdateCodeList.Contains(UpdRec.UpdateCode)) { continue; } if (UpdateRecs.ContainsKey(UpdRec.StudentID)) { UpdateRecs[UpdRec.StudentID].Add(UpdRec); } } }; loader1.Run(e.List); }; wizard.ValidateRow += delegate(object sender, SmartSchool.API.PlugIn.Import.ValidateRowEventArgs e) { int i = 0; DateTime dt; // 檢查學生是否存在 SHStudentRecord studRec = null; if (Students.ContainsKey(e.Data.ID)) { studRec = Students[e.Data.ID]; } else { e.ErrorMessage = "沒有這位學生" + e.Data.ID; return; } // 驗證格式資料 bool InputFormatPass = true; foreach (string field in e.SelectFields) { string value = e.Data[field].Trim(); //// 驗證$無法匯入 //if (value.IndexOf('$') > -1) //{ // e.ErrorFields.Add(field, "儲存格有$無法匯入."); // break; //} switch (field) { default: break; //// 班別 //case "班別": break; //// 特殊身份代碼 //case "特殊身份代碼": break; //// 異動科別 //case "異動科別": break; //// 年級 //case "年級": break; //// 異動學號 //case "異動學號": break; //// 異動姓名 //case "異動姓名": break; //// 身分證號 //case "身分證號": break; //// 註1 //case "註1": break; //// 異動種類 //case "異動種類": break; // 異動代碼 case "異動代碼": if (!_UpdateCodeList.Contains(value)) { InputFormatPass &= false; e.ErrorFields.Add(field, "非學籍異動代碼!"); } break; // 異動日期(必填) case "異動日期": DateTime dtC1; if (DateTime.TryParse(value, out dtC1)) { } else { InputFormatPass &= false; e.ErrorFields.Add(field, "日期錯誤!"); } break; case "備查日期": case "核准日期": DateTime dtC2; if (value.Trim() != "") { if (DateTime.TryParse(value, out dtC2)) { } else { InputFormatPass &= false; e.ErrorFields.Add(field, "日期錯誤!"); } } break; //// 原因及事項 //case "原因及事項": break; //// 新學號 //case "新學號": break; //// 更正後資料 //case "更正後資料": break; //// 舊班別 //case "舊班別": break; //// 舊科別代碼 //case "舊科別代碼": break; //// 備查日期 //case "備查日期": // break; //// 備查文號 //case "備查文號": break; //// 核准日期 //case "核准日期": break; //// 核准文號 //case "核准文號": break; //// 備註 //case "備註": break; } } }; wizard.ImportPackage += delegate(object sender, SmartSchool.API.PlugIn.Import.ImportPackageEventArgs e) { Dictionary <string, List <RowData> > id_Rows = new Dictionary <string, List <RowData> >(); foreach (RowData data in e.Items) { if (!id_Rows.ContainsKey(data.ID)) { id_Rows.Add(data.ID, new List <RowData>()); } id_Rows[data.ID].Add(data); } List <SHUpdateRecordRecord> InsertList = new List <SHUpdateRecordRecord>(); List <SHUpdateRecordRecord> UpdateList = new List <SHUpdateRecordRecord>(); // 檢查新增或更新方式: // 每筆 Key 為:異動日期+異動代碼+原因及事項,如果三者內容相同更新,如果不同就新增。 foreach (string id in id_Rows.Keys) { DateTime dt; // 讀取工作表內資料 foreach (RowData data in id_Rows[id]) { // 當異動記錄內沒有工作表讀取轉換後學生ID,就跳過。 if (!UpdateRecs.ContainsKey(id)) { continue; } DateTime.TryParse(data["異動日期"], out dt); // 異動代碼 string UpdateCode = string.Empty; if (data.ContainsKey("異動代碼")) { UpdateCode = data["異動代碼"]; } // 取得原因及事項 string UpdateDesc = string.Empty; if (data.ContainsKey("原因及事項")) { UpdateDesc = data["原因及事項"]; } SHUpdateRecordRecord updateRec = null; // 異動日期+異動代碼 (如果相同有當更新,不同就新增) foreach (SHUpdateRecordRecord urr in UpdateRecs[id]) { if (UpdateCode == urr.UpdateCode) { DateTime dt1; DateTime.TryParse(urr.UpdateDate, out dt1); if (dt == dt1) { // 使用原因及事項當作Key if (UpdateDesc == urr.UpdateDescription) { updateRec = urr; } } } } bool isInsert = true; if (updateRec == null) { updateRec = new SHUpdateRecordRecord(); updateRec.StudentID = id; } else { isInsert = false; } // 這段在做資料填入異動紀錄 foreach (string field in e.ImportFields) { string value = data[field].Trim(); switch (field) { // 班別 case "班別": updateRec.ClassType = value; break; // 特殊身份代碼 case "特殊身份代碼": updateRec.SpecialStatus = value; break; // 異動科別 case "異動科別": updateRec.Department = value; break; // 年級 case "年級": updateRec.GradeYear = value; break; // 異動學號 case "異動學號": updateRec.StudentNumber = value; break; // 異動姓名 case "異動姓名": updateRec.StudentName = value; break; // 身分證號 case "身分證號": updateRec.IDNumber = value; break; // 註1 case "註1": updateRec.IDNumberComment = value; break; //// 異動種類 //case "異動種類": // break; // 異動代碼 case "異動代碼": updateRec.UpdateCode = value; break; // 異動日期 case "異動日期": DateTime dt1; if (DateTime.TryParse(value, out dt1)) { updateRec.UpdateDate = dt1.ToShortDateString(); } break; // 原因及事項 case "原因及事項": updateRec.UpdateDescription = value; break; // 新學號 case "新學號": updateRec.NewStudentNumber = value; break; // 更正後資料 case "更正後資料": updateRec.NewData = value; break; // 舊班別 case "舊班別": updateRec.OldClassType = value; break; // 舊科別代碼 case "舊科別代碼": updateRec.OldDepartmentCode = value; break; // 備查日期 case "備查日期": DateTime dt2; if (DateTime.TryParse(value, out dt2)) { updateRec.LastADDate = dt2.ToShortDateString(); } break; // 備查文號 case "備查文號": updateRec.LastADNumber = value; break; // 核准日期 case "核准日期": DateTime dt3; if (DateTime.TryParse(value, out dt3)) { updateRec.ADDate = dt3.ToShortDateString(); } break; // 核准文號 case "核准文號": updateRec.ADNumber = value; break; // 備註 case "備註": updateRec.GraduateComment = value; break; } } if (string.IsNullOrEmpty(updateRec.StudentID) || string.IsNullOrEmpty(updateRec.UpdateDate) || string.IsNullOrEmpty(updateRec.UpdateCode)) { continue; } else { if (isInsert) { InsertList.Add(updateRec); } else { UpdateList.Add(updateRec); } } } } try { if (InsertList.Count > 0) { Insert(InsertList); } if (UpdateList.Count > 0) { Update(UpdateList); } PermRecLogProcess prlp = new PermRecLogProcess(); prlp.SaveLog("學生.匯入異動", "匯入學籍異動", "匯入學籍異動:共新增" + InsertList.Count + "筆資料,共更新:" + UpdateList.Count + "筆資料"); SmartSchool.StudentRelated.Student.Instance.SyncAllBackground(); } catch (Exception ex) { } }; }
private void frmSchoolYear_Load(object sender, EventArgs e) { //取得選取學生 StudentRecords = SHStudent.SelectByIDs(K12.Presentation.NLDPanels.Student.SelectedSource); }
/// <summary> /// 產生新生異動(傳入學生編號、異動日期、異動代碼、班別) /// </summary> /// <param name="StudentIDList"></param> /// <param name="UpdateDate"></param> /// <param name="UpdateCode"></param> /// <param name="ClassType"></param> /// <returns></returns> public bool Run(List <string> StudentIDList, string UpdateDate, string UpdateCode, string UpdateDesc, string ClassType) { bool pass = true; List <SHBeforeEnrollmentRecord> befRecList = SHBeforeEnrollment.SelectByStudentIDs(StudentIDList); Dictionary <string, DAL.SchoolData> schoolDataDict = new Dictionary <string, DAL.SchoolData> (); foreach (XElement elm in BL.Get.JHSchoolList().Elements("學校")) { DAL.SchoolData sd = new DAL.SchoolData(); sd.SchoolCode = elm.Attribute("代碼").Value; sd.SchoolLocation = elm.Attribute("所在地").Value; sd.SchoolName = elm.Attribute("名稱").Value; sd.SchoolLocationCode = elm.Attribute("所在地代碼").Value; if (sd.SchoolCode.Length > 3) { sd.SchoolType = sd.SchoolCode.Substring(2, 1); } string s1 = elm.Attribute("所在地").Value + elm.Attribute("名稱").Value; if (!schoolDataDict.ContainsKey(s1)) { schoolDataDict.Add(s1, sd); } if (!schoolDataDict.ContainsKey(sd.SchoolName)) { schoolDataDict.Add(sd.SchoolName, sd); } } int SchoolYear = 0, Semester = 0; int.TryParse(K12.Data.School.DefaultSchoolYear, out SchoolYear); int.TryParse(K12.Data.School.DefaultSemester, out Semester); List <string> _CheckCodeList = (from data in _UpdateCodeList select data.Substring(0, 3)).ToList(); List <SHUpdateRecordRecord> insertData = new List <SHUpdateRecordRecord>(); List <SHUpdateRecordRecord> WaitDeleteData = new List <SHUpdateRecordRecord>(); // 取得學生資料 List <SHStudentRecord> studRecList = SHStudent.SelectByIDs(StudentIDList); List <string> SIDList = new List <string>(); // 取得已有新生異動 foreach (SHUpdateRecordRecord rec in SHUpdateRecord.SelectByStudentIDs(StudentIDList)) { if (_CheckCodeList.Contains(rec.UpdateCode)) { WaitDeleteData.Add(rec); if (!SIDList.Contains(rec.StudentID)) { SIDList.Add(rec.StudentID); } } } bool checkdelData = true; // 已有資料是否覆蓋 if (SIDList.Count > 0) { WarningForm wf = new WarningForm(); wf.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; wf.SetStudentCount(SIDList.Count); wf.SetStudRec(studRecList); wf.SetUpdateRecList(WaitDeleteData); if (wf.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) { checkdelData = false; pass = false; } } // 清掉舊資料 if (checkdelData) { SHUpdateRecord.Delete(WaitDeleteData); } // 取得新生異動 foreach (SHStudentRecord studRec in studRecList) { // 不刪除代表不需要新增,所以略過 if (checkdelData == false) { if (SIDList.Contains(studRec.ID)) { continue; } } SHUpdateRecordRecord NewUpdateRec = new SHUpdateRecordRecord(); if (SchoolYear > 0) { NewUpdateRec.SchoolYear = SchoolYear; } if (Semester > 0) { NewUpdateRec.Semester = Semester; } if (studRec.Class != null) { if (studRec.Class.GradeYear.HasValue) { NewUpdateRec.GradeYear = studRec.Class.GradeYear.Value.ToString(); } } NewUpdateRec.GraduateComment = ""; NewUpdateRec.UpdateCode = UpdateCode; NewUpdateRec.UpdateDescription = UpdateDesc; NewUpdateRec.UpdateDate = UpdateDate; NewUpdateRec.ClassType = ClassType; NewUpdateRec.SpecialStatus = DAL.DALTransfer.GetSpecialCode(studRec.ID); if (studRec.Department != null) { NewUpdateRec.Department = studRec.Department.FullName; } NewUpdateRec.StudentID = studRec.ID; NewUpdateRec.StudentName = studRec.Name; NewUpdateRec.StudentNumber = studRec.StudentNumber; NewUpdateRec.IDNumber = studRec.IDNumber; if (studRec.Birthday.HasValue) { NewUpdateRec.Birthdate = studRec.Birthday.Value.ToShortDateString(); } NewUpdateRec.Gender = studRec.Gender; if (int.Parse(UpdateCode) > 5) { NewUpdateRec.GraduateComment = "1"; } foreach (SHBeforeEnrollmentRecord brfRec in befRecList) { if (brfRec.RefStudentID == NewUpdateRec.StudentID) { NewUpdateRec.GraduateSchool = brfRec.School; NewUpdateRec.GraduateSchoolYear = brfRec.GraduateSchoolYear; // 用學校名稱解析 if (!string.IsNullOrEmpty(brfRec.School)) { string key = brfRec.SchoolLocation.Replace("台", "臺") + brfRec.School.Trim(); if (schoolDataDict.ContainsKey(key)) { NewUpdateRec.GraduateSchoolCode = schoolDataDict[key].SchoolCode; NewUpdateRec.GraduateSchoolLocationCode = schoolDataDict[key].SchoolLocationCode; } } } } insertData.Add(NewUpdateRec); } // 新增異動 SHUpdateRecord.Insert(insertData); return(pass); }
private void wizard1_FinishButtonClick(object sender, CancelEventArgs e) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Title = "另存新檔"; saveFileDialog1.FileName = "" + _Title + ".xls"; saveFileDialog1.Filter = "Excel (*.xls)|*.xls|所有檔案 (*.*)|*.*"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { List <string> idlist = new List <string>(); #region 取得選取學生編號 List <SHStudentRecord> selectedStudents = SHStudent.SelectByIDs(K12.Presentation.NLDPanels.Student.SelectedSource); foreach (SHStudentRecord stu in selectedStudents) { if (!idlist.Contains(stu.ID)) { idlist.Add(stu.ID); } } #endregion List <string> studentFieldList = new List <string>(); List <string> exportFieldList = new List <string>(_SelectedFields); #region 取得選取欄位 for (int index = 0; index < 5; index++) { if (listViewEx1.Items[index] != null && listViewEx1.Items[index].Checked) { studentFieldList.Add(listViewEx1.Items[index].Text.Trim()); } } #endregion List <List <string> > splitList = new List <List <string> >(); //把全部學生以_PackageLimint人分一包 #region 把全部學生以_PackageLimint人分一包 int count = 0; List <string> package = new List <string>(); foreach (string id in idlist) { if (count == 0) { count = (splitList.Count + 1) * 50; count = count > _PackageLimint ? _PackageLimint : count; package = new List <string>(_PackageLimint); splitList.Add(package); } package.Add(id); count--; } #endregion //兩條獨立讀取 Dictionary <List <string>, ManualResetEvent> Loader1 = new Dictionary <List <string>, ManualResetEvent>(); Dictionary <List <string>, ManualResetEvent> Loader2 = new Dictionary <List <string>, ManualResetEvent>(); //已讀取資料 Dictionary <ManualResetEvent, List <RowData> > Filler = new Dictionary <ManualResetEvent, List <RowData> >(); int i = 0; foreach (List <string> p in splitList) { ManualResetEvent handleEvent = new ManualResetEvent(false); if ((i & 1) == 0) { Loader1.Add(p, handleEvent); } else { Loader2.Add(p, handleEvent); } Filler.Add(handleEvent, new List <RowData>()); i++; } //在背景執行取得資料 BackgroundWorker bkwDataLoader = new BackgroundWorker(); bkwDataLoader.DoWork += new DoWorkEventHandler(bkwDataLoader_DoWork); bkwDataLoader.RunWorkerAsync(new object[] { Loader1, Filler, exportFieldList }); bkwDataLoader = new BackgroundWorker(); bkwDataLoader.DoWork += new DoWorkEventHandler(bkwDataLoader_DoWork); bkwDataLoader.RunWorkerAsync(new object[] { Loader2, Filler, exportFieldList }); //在背景計算不及格名單 BackgroundWorker bkwNotPassComputer = new BackgroundWorker(); bkwNotPassComputer.WorkerReportsProgress = true; bkwNotPassComputer.DoWork += new DoWorkEventHandler(bkwNotPassComputer_DoWork); bkwNotPassComputer.ProgressChanged += new ProgressChangedEventHandler(bkwNotPassComputer_ProgressChanged); bkwNotPassComputer.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bkwNotPassComputer_RunWorkerCompleted); bkwNotPassComputer.RunWorkerAsync(new object[] { saveFileDialog1.FileName, studentFieldList, exportFieldList, Filler }); this.Close(); } }
public override void InitializeExport(SmartSchool.API.PlugIn.Export.ExportWizard wizard) { wizard.ExportableFields.AddRange("姓名", "學號", "班級", "座號", "必選修", "校部訂", "學生狀態"); wizard.ExportPackage += delegate(object sender, SmartSchool.API.PlugIn.Export.ExportPackageEventArgs e) { //課程資訊 List <SHCourseRecord> courses = SHCourse.SelectByIDs(e.List); //學生修課資訊 Dictionary <string, List <SHSCAttendRecord> > scattends = new Dictionary <string, List <SHSCAttendRecord> >(); //課程修課學生 Dictionary <string, SHStudentRecord> students = new Dictionary <string, SHStudentRecord>(); #region 取得修課記錄 foreach (SHSCAttendRecord record in SHSCAttend.SelectByStudentIDAndCourseID(new string[] { }, e.List)) { if (!scattends.ContainsKey(record.RefCourseID)) { scattends.Add(record.RefCourseID, new List <SHSCAttendRecord>()); } scattends[record.RefCourseID].Add(record); if (!students.ContainsKey(record.RefStudentID)) { students.Add(record.RefStudentID, null); } } #endregion #region 取得學生資訊 SHStudent.RemoveAll(); foreach (SHStudentRecord record in SHStudent.SelectByIDs(new List <string>(students.Keys))) { if (students.ContainsKey(record.ID)) { students[record.ID] = record; } } #endregion #region 產生 Row Data foreach (SHCourseRecord course in courses) { //Debug if (!scattends.ContainsKey(course.ID)) { continue; } foreach (SHSCAttendRecord record in scattends[course.ID]) { RowData row = new RowData(); row.ID = course.ID; foreach (string field in e.ExportFields) { if (wizard.ExportableFields.Contains(field)) { switch (field) { case "姓名": row.Add(field, students[record.RefStudentID].Name); break; case "學號": row.Add(field, students[record.RefStudentID].StudentNumber); break; case "班級": row.Add(field, (students[record.RefStudentID].Class != null ? students[record.RefStudentID].Class.Name : "")); break; case "座號": row.Add(field, "" + students[record.RefStudentID].SeatNo); break; case "必選修": if (record.Required) { row.Add(field, "" + "必修"); } else { row.Add(field, "" + "選修"); } break; case "校部訂": row.Add(field, "" + record.RequiredBy); break; case "學生狀態": row.Add(field, "" + students[record.RefStudentID].Status.ToString()); break; } } } e.Items.Add(row); } } #endregion ApplicationLog.Log("成績系統.匯入匯出", "匯出課程修課學生", "總共匯出" + e.Items.Count + "筆課程修課學生。"); }; }
public ImportStartupForm() { InitializeComponent(); InitializeSemesters(); //_effortMapper = new EffortMapper(); // 載入預設儲存值 LoadConfigData(); _worker = new BackgroundWorker(); _worker.WorkerReportsProgress = true; _worker.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e) { lblMessage.Text = "" + e.UserState; }; _worker.DoWork += delegate(object sender, DoWorkEventArgs e) { #region Worker DoWork _worker.ReportProgress(0, "訊息:檢查讀卡文字格式…"); #region 檢查文字檔 ValidateTextFiles vtf = new ValidateTextFiles(StudentNumberMax); ValidateTextResult vtResult = vtf.CheckFormat(_files); if (vtResult.Error) { e.Result = vtResult; return; } #endregion //文字檔轉 RawData RawDataCollection rdCollection = new RawDataCollection(); rdCollection.ConvertFromFiles(_files); //RawData 轉 DataRecord DataRecordCollection drCollection = new DataRecordCollection(); drCollection.ConvertFromRawData(rdCollection); _rawDataValidator = new DataValidator <RawData>(); _dataRecordValidator = new DataValidator <DataRecord>(); #region 取得驗證需要的資料 SHCourse.RemoveAll(); _worker.ReportProgress(5, "訊息:取得學生資料…"); List <StudentObj> studentList = GetInSchoolStudents(); List <string> s_ids = new List <string>(); Dictionary <string, List <string> > studentNumberToStudentIDs = new Dictionary <string, List <string> >(); foreach (StudentObj student in studentList) { string sn = student.StudentNumber;// SCValidatorCreator.GetStudentNumberFormat(student.StudentNumber); if (!studentNumberToStudentIDs.ContainsKey(sn)) { studentNumberToStudentIDs.Add(sn, new List <string>()); } studentNumberToStudentIDs[sn].Add(student.StudentID); } foreach (string each in studentNumberToStudentIDs.Keys) { if (studentNumberToStudentIDs[each].Count > 1) { //學號重覆 } } foreach (var dr in drCollection) { if (studentNumberToStudentIDs.ContainsKey(dr.StudentNumber)) { s_ids.AddRange(studentNumberToStudentIDs[dr.StudentNumber]); } } studentList.Clear(); _worker.ReportProgress(10, "訊息:取得課程資料…"); List <SHCourseRecord> courseList = SHCourse.SelectBySchoolYearAndSemester(SchoolYear, Semester); List <SHAEIncludeRecord> aeList = SHAEInclude.SelectAll(); //List<JHSCAttendRecord> scaList = JHSCAttend.SelectAll(); var c_ids = from course in courseList select course.ID; _worker.ReportProgress(15, "訊息:取得修課資料…"); //List<JHSCAttendRecord> scaList2 = JHSCAttend.SelectByStudentIDAndCourseID(s_ids, c_ids.ToList<string>()); List <SHSCAttendRecord> scaList = new List <SHSCAttendRecord>(); FunctionSpliter <string, SHSCAttendRecord> spliter = new FunctionSpliter <string, SHSCAttendRecord>(300, 3); spliter.Function = delegate(List <string> part) { return(SHSCAttend.Select(part, c_ids.ToList <string>(), null, SchoolYear.ToString(), Semester.ToString())); }; scaList = spliter.Execute(s_ids); _worker.ReportProgress(20, "訊息:取得試別資料…"); List <SHExamRecord> examList = SHExam.SelectAll(); #endregion #region 註冊驗證 _worker.ReportProgress(30, "訊息:載入驗證規則…"); _rawDataValidator.Register(new SubjectCodeValidator()); _rawDataValidator.Register(new ClassCodeValidator()); _rawDataValidator.Register(new ExamCodeValidator()); SCValidatorCreator scCreator = new SCValidatorCreator(SHStudent.SelectByIDs(s_ids), courseList, scaList); _dataRecordValidator.Register(scCreator.CreateStudentValidator()); _dataRecordValidator.Register(new ExamValidator(examList)); _dataRecordValidator.Register(scCreator.CreateSCAttendValidator()); _dataRecordValidator.Register(new CourseExamValidator(scCreator.StudentCourseInfo, aeList, examList)); #endregion #region 進行驗證 _worker.ReportProgress(45, "訊息:進行驗證中…"); List <string> msgList = new List <string>(); foreach (RawData rawData in rdCollection) { List <string> msgs = _rawDataValidator.Validate(rawData); msgList.AddRange(msgs); } if (msgList.Count > 0) { e.Result = msgList; return; } foreach (DataRecord dataRecord in drCollection) { List <string> msgs = _dataRecordValidator.Validate(dataRecord); msgList.AddRange(msgs); } if (msgList.Count > 0) { e.Result = msgList; return; } #endregion #region 取得學生的評量成績 _worker.ReportProgress(65, "訊息:取得學生評量成績…"); _deleteScoreList.Clear(); _addScoreList.Clear(); AddScoreDic.Clear(); //var student_ids = from student in scCreator.StudentNumberDictionary.Values select student.ID; //List<string> course_ids = scCreator.AttendCourseIDs; var scaIDs = from sca in scaList select sca.ID; Dictionary <string, SHSCETakeRecord> sceList = new Dictionary <string, SHSCETakeRecord>(); FunctionSpliter <string, SHSCETakeRecord> spliterSCE = new FunctionSpliter <string, SHSCETakeRecord>(300, 3); spliterSCE.Function = delegate(List <string> part) { return(SHSCETake.Select(null, null, null, null, part)); }; foreach (SHSCETakeRecord sce in spliterSCE.Execute(scaIDs.ToList())) { string key = GetCombineKey(sce.RefStudentID, sce.RefCourseID, sce.RefExamID); if (!sceList.ContainsKey(key)) { sceList.Add(key, sce); } } Dictionary <string, SHExamRecord> examTable = new Dictionary <string, SHExamRecord>(); Dictionary <string, SHSCAttendRecord> scaTable = new Dictionary <string, SHSCAttendRecord>(); foreach (SHExamRecord exam in examList) { if (!examTable.ContainsKey(exam.Name)) { examTable.Add(exam.Name, exam); } } foreach (SHSCAttendRecord sca in scaList) { string key = GetCombineKey(sca.RefStudentID, sca.RefCourseID); if (!scaTable.ContainsKey(key)) { scaTable.Add(key, sca); } } _worker.ReportProgress(80, "訊息:成績資料建立…"); foreach (DataRecord dr in drCollection) { SHStudentRecord student = student = scCreator.StudentNumberDictionary[dr.StudentNumber]; SHExamRecord exam = examTable[dr.Exam]; List <SHCourseRecord> courses = new List <SHCourseRecord>(); foreach (SHCourseRecord course in scCreator.StudentCourseInfo.GetCourses(dr.StudentNumber)) { if (dr.Subjects.Contains(course.Subject)) { courses.Add(course); } } foreach (SHCourseRecord course in courses) { string key = GetCombineKey(student.ID, course.ID, exam.ID); if (sceList.ContainsKey(key)) { _deleteScoreList.Add(sceList[key]); } SHSCETakeRecord sh = new SHSCETakeRecord(); sh.RefCourseID = course.ID; sh.RefExamID = exam.ID; sh.RefSCAttendID = scaTable[GetCombineKey(student.ID, course.ID)].ID; sh.RefStudentID = student.ID; //轉型Double再轉回decimal,可去掉小數點後的0 double reScore = (double)dr.Score; decimal Score = decimal.Parse(reScore.ToString()); if (Global.StudentDocRemove) { string qq = Score.ToString(); if (qq.Contains(".")) { string[] kk = qq.Split('.'); sh.Score = decimal.Parse(kk[0]); } else { // sh.Score = decimal.Parse(Score.ToString()); } } else { sh.Score = decimal.Parse(Score.ToString()); } //sceNew.Effort = _effortMapper.GetCodeByScore(dr.Score); //是否有重覆的學生,課程,評量 if (!AddScoreDic.ContainsKey(sh.RefStudentID + "_" + course.ID + "_" + exam.ID)) { _addScoreList.Add(sh); AddScoreDic.Add(sh.RefStudentID + "_" + course.ID + "_" + exam.ID, sh); } } } #endregion _worker.ReportProgress(100, "訊息:背景作業完成…"); e.Result = null; #endregion }; _worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) { #region Worker Completed if (e.Error == null && e.Result == null) { if (!_upload.IsBusy) { //如果學生身上已有成績,則提醒使用者 if (_deleteScoreList.Count > 0) { _warn.RunWorkerAsync(); } else { lblMessage.Text = "訊息:成績上傳中…"; FISCA.Presentation.MotherForm.SetStatusBarMessage("成績上傳中…", 0); counter = 0; _upload.RunWorkerAsync(); } } } else { ControlEnable = true; if (e.Error != null) { MsgBox.Show("匯入失敗。" + e.Error.Message); SmartSchool.ErrorReporting.ReportingService.ReportException(e.Error); } else if (e.Result != null && e.Result is ValidateTextResult) { ValidateTextResult result = e.Result as ValidateTextResult; ValidationErrorViewer viewer = new ValidationErrorViewer(); viewer.SetTextFileError(result.LineIndexes, result.ErrorFormatLineIndexes, result.DuplicateLineIndexes); viewer.ShowDialog(); } else if (e.Result != null && e.Result is List <string> ) { ValidationErrorViewer viewer = new ValidationErrorViewer(); viewer.SetErrorLines(e.Result as List <string>); viewer.ShowDialog(); } } #endregion }; _upload = new BackgroundWorker(); _upload.WorkerReportsProgress = true; _upload.ProgressChanged += new ProgressChangedEventHandler(_upload_ProgressChanged); _upload.DoWork += new DoWorkEventHandler(_upload_DoWork); _upload.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_upload_RunWorkerCompleted); _warn = new BackgroundWorker(); _warn.WorkerReportsProgress = true; _warn.DoWork += delegate(object sender, DoWorkEventArgs e) { _warn.ReportProgress(0, "產生警告訊息..."); examDict = new Dictionary <string, string>(); foreach (SHExamRecord exam in SHExam.SelectAll()) { if (!examDict.ContainsKey(exam.ID)) { examDict.Add(exam.ID, exam.Name); } } WarningForm form = new WarningForm(); int count = 0; foreach (SHSCETakeRecord sce in _deleteScoreList) { // 當成績資料是空值跳過 //if (sce.Score.HasValue == false && sce.Effort.HasValue == false && string.IsNullOrEmpty(sce.Text)) //if (sce.Score == null && string.IsNullOrEmpty(sce.Text)) // continue; count++; SHStudentRecord student = SHStudent.SelectByID(sce.RefStudentID); SHCourseRecord course = SHCourse.SelectByID(sce.RefCourseID); string exam = (examDict.ContainsKey(sce.RefExamID) ? examDict[sce.RefExamID] : "<未知的試別>"); string s = ""; if (student.Class != null) { s += student.Class.Name; } if (!string.IsNullOrEmpty("" + student.SeatNo)) { s += " " + student.SeatNo + "號"; } if (!string.IsNullOrEmpty(student.StudentNumber)) { s += " (" + student.StudentNumber + ")"; } s += " " + student.Name; string scoreName = sce.RefStudentID + "_" + sce.RefCourseID + "_" + sce.RefExamID; if (AddScoreDic.ContainsKey(scoreName)) { form.AddMessage(student.ID, s, string.Format("學生在「{0}」課程「{1}」中已有成績「{2}」將修改為「{3}」。", course.Name, exam, sce.Score, AddScoreDic[scoreName].Score)); } else { form.AddMessage(student.ID, s, string.Format("學生在「{0}」課程「{1}」中已有成績「{2}」。", course.Name, exam, sce.Score)); } _warn.ReportProgress((int)(count * 100 / _deleteScoreList.Count), "產生警告訊息..."); } e.Result = form; }; _warn.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) { WarningForm form = e.Result as WarningForm; if (form.ShowDialog() == DialogResult.OK) { lblMessage.Text = "訊息:成績上傳中…"; FISCA.Presentation.MotherForm.SetStatusBarMessage("成績上傳中…", 0); counter = 0; _upload.RunWorkerAsync(); } else { this.DialogResult = DialogResult.Cancel; } }; _warn.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e) { FISCA.Presentation.MotherForm.SetStatusBarMessage("" + e.UserState, e.ProgressPercentage); }; _files = new List <FileInfo>(); _addScoreList = new List <SHSCETakeRecord>(); _deleteScoreList = new List <SHSCETakeRecord>(); AddScoreDic = new Dictionary <string, SHSCETakeRecord>(); examDict = new Dictionary <string, string>(); }