//кнопка экспорта
        private async void button1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                DialogResult res = MessageBox.Show("Вы действительно хотите экспортировать выбранную сделку в MS Word?", "Экспорт сделки", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
                switch (res)
                {
                case DialogResult.OK:
                    SqlCommand getApartmentsInfoCommand = new SqlCommand("SELECT [ValueTransactions], [ValueFirm], [ValueRealtor], [SqaureApartments], [FloorApartments], [ValueApartments], [AreaApartments], [RoomsApartments], [AddressApartments], [EmailClients], [SNMRealtors], [SNMClients], [DateTransactions], [PercentFromDeal], [EmailRealtors], [BudgetClients] FROM [Transactions] WHERE [Id]=@Id", sqlConnection);
                    getApartmentsInfoCommand.Parameters.AddWithValue("Id", Convert.ToInt32(listView1.SelectedItems[0].SubItems[0].Text));
                    SqlDataReader sqlReader = null;
                    try
                    {
                        sqlReader = await getApartmentsInfoCommand.ExecuteReaderAsync();

                        while (await sqlReader.ReadAsync())
                        {
                            try
                            {
                                var helper            = new WordHelper(@"C:\Users\User\source\repos\RealEstateAgency\RealEstateAgency\bin\Debug\transactions\transaction.docx");
                                var realtor           = Convert.ToString(sqlReader["SNMRealtors"]);
                                var client            = Convert.ToString(sqlReader["SNMClients"]);
                                var idTransaction     = Convert.ToString(listView1.SelectedItems[0].SubItems[0].Text);
                                var date              = Convert.ToString(sqlReader["DateTransactions"]);
                                var percentRealtor    = Convert.ToString(sqlReader["PercentFromDeal"]);
                                var emailRealtor      = Convert.ToString(sqlReader["EmailRealtors"]);
                                var budget            = Convert.ToString(sqlReader["BudgetClients"]);
                                var emailClient       = Convert.ToString(sqlReader["EmailClients"]);
                                var address           = Convert.ToString(sqlReader["AddressApartments"]);
                                var area              = Convert.ToString(sqlReader["AreaApartments"]);
                                var value             = Convert.ToString(sqlReader["ValueApartments"]);
                                var rooms             = Convert.ToString(sqlReader["RoomsApartments"]);
                                var floor             = Convert.ToString(sqlReader["FloorApartments"]);
                                var sqaure            = Convert.ToString(sqlReader["SqaureApartments"]);
                                var valueRealtor      = Convert.ToString(sqlReader["ValueRealtor"]);
                                var valueFirm         = Convert.ToString(sqlReader["ValueFirm"]);
                                var valueTransactions = Convert.ToString(sqlReader["ValueTransactions"]);
                                var items             = new Dictionary <string, string>
                                {
                                    { "{Realtor}", realtor },
                                    { "{Client}", client },
                                    { "{Id}", idTransaction },
                                    { "{Date}", date },
                                    { "{PercentRealtor}", percentRealtor },
                                    { "{EmailRealtor}", emailRealtor },
                                    { "{Budget}", budget },
                                    { "{EmailClient}", emailClient },
                                    { "{Address}", address },
                                    { "{Area}", area },
                                    { "{Value}", value },
                                    { "{Rooms}", rooms },
                                    { "{Floor}", floor },
                                    { "{Sqaure}", sqaure },
                                    { "{ValueRealtor}", valueRealtor },
                                    { "{ValueFirm}", valueFirm },
                                    { "{ValueTransaction}", valueTransactions },
                                };
                                helper.Process(items);
                                MessageBox.Show("Вы успешно экспортировали сделку в MS Word! Пожалуйста, зайдите в директорию, где у вас хранятся сделки.", "Экспорт сделки", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        if (sqlReader != null && !sqlReader.IsClosed)
                        {
                            sqlReader.Close();
                        }
                    }
                    break;
                }
            }
            else
            {
                MessageBox.Show("Ни одна строка не была выделена!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#2
0
        public void Writer(Document doc)
        {
            DocumentBuilder builder = new DocumentBuilder(doc);

            _warned = false;
            _domainText.Clear();

            if (SemesterScoreRecord == null)
            {
                builder.MoveToMergeField("成績_start");
                builder.MoveToMergeField("成績_end");
                builder.MoveToMergeField("文字描述");
                return;
            }

            builder.MoveToMergeField("成績_start");
            Cell startCell = builder.CurrentParagraph.ParentNode as Cell;

            builder.MoveToMergeField("成績_end");
            Cell endCell = builder.CurrentParagraph.ParentNode as Cell;

            Table table    = startCell.ParentRow.ParentTable;
            int   rowCount = table.IndexOf(endCell.ParentRow) - table.IndexOf(startCell.ParentRow) + 1;
            Font  font     = builder.Font;

            #region 填入學習領域總成績
            if (_printLearnDomain)
            {
                rowCount--;
                WordHelper.MergeHorizontalCell(endCell, 2);
                Cell scoreCell = endCell.NextSibling.NextSibling as Cell;
                WordHelper.MergeHorizontalCell(scoreCell, 2);

                WordHelper.Write(endCell, font, "學習領域總成績");
                WordHelper.Write(scoreCell, font, SemesterScoreRecord.LearnDomainScore.HasValue ? _degreeMapper.GetDegreeByScore(SemesterScoreRecord.LearnDomainScore.Value) : "");
            }
            #endregion

            #region 整理成 Domain -> List<Subject>
            Dictionary <string, List <SubjectScore> > domainSubjects = new Dictionary <string, List <SubjectScore> >();

            foreach (var subject in SemesterScoreRecord.Subjects.Values)
            {
                if (!domainSubjects.ContainsKey(subject.Domain))
                {
                    domainSubjects.Add(subject.Domain, new List <SubjectScore>());
                }
                domainSubjects[subject.Domain].Add(subject);
            }

            string printsocre = _config.GetString("領域科目設定", "Domain");
            if (printsocre == "Domain")
            {
                // 沒有科目成績只有領域成績時加入領域名稱(轉學生用到)
                foreach (DomainScore domin in SemesterScoreRecord.Domains.Values)
                {
                    if (!domainSubjects.ContainsKey(domin.Domain))
                    {
                        domainSubjects.Add(domin.Domain, new List <SubjectScore>());
                    }

                    // 處理新竹語文呈現
                    if (domin.Domain == "語文")
                    {
                        int co = 0;
                        foreach (SubjectScore ss in SemesterScoreRecord.Subjects.Values)
                        {
                            if (ss.Domain == "語文")
                            {
                                co++;
                            }
                        }
                        if (co == 0)
                        {
                            if (!_domainsWithoutDetail.Contains(domin.Domain))
                            {
                                _domainsWithoutDetail.Add(domin.Domain);
                            }
                        }
                    }
                }
            }

            foreach (List <SubjectScore> subjectScoreList in domainSubjects.Values)
            {
                subjectScoreList.Sort(delegate(SubjectScore x, SubjectScore y)
                {
                    return(JHSchool.Evaluation.Subject.CompareSubjectOrdinal(x.Subject, y.Subject));
                });
            }
            #endregion

            #region 檢查成績項目是否超出可列印行數
            int count = 0;
            foreach (string domain in Global.GetDomainList())
            {
                if (_domainsWithoutDetail.Contains(domain))
                {
                    count++;
                }
                else if (domainSubjects.ContainsKey(domain))
                {
                    count += domainSubjects[domain].Count;
                }
            }

            if (count > rowCount && _warned == false)
            {
                MsgBox.Show("成績項目超出可列印行數,部分成績將不會列在報表上。");
                _warned = true;
            }
            #endregion

            #region 填學期成績
            Cell          currentCell = startCell;
            List <string> list        = new List <string>(domainSubjects.Keys);

            // 當只有領域成績
            if (list.Count == 0)
            {
                foreach (var domain in SemesterScoreRecord.Domains.Values)
                {
                    list.Add(domain.Domain);
                }
            }


            list.Sort(JHSchool.Evaluation.Subject.CompareDomainOrdinal);
            foreach (string domain in list)
            {
                if (_domainsWithoutDetail.Contains(domain))
                {
                    #region 只列印領域成績
                    if (!SemesterScoreRecord.Domains.ContainsKey(domain))
                    {
                        continue;
                    }
                    rowCount--;

                    DomainScore domainScore = SemesterScoreRecord.Domains[domain];

                    string group = JHSchool.Evaluation.Subject.GetDomainGroup(domain);
                    if (Global.Params["Mode"] == "KaoHsiung" &&
                        !string.IsNullOrEmpty(group))
                    {
                        currentCell.CellFormat.VerticalMerge = CellMerge.First;
                        WordHelper.Write(currentCell, font, group);
                        WordHelper.Write(currentCell.NextSibling as Cell, font, domain);
                    }
                    else
                    {
                        WordHelper.MergeHorizontalCell(currentCell, 2);
                        WordHelper.Write(currentCell, font, domain);
                    }

                    Cell scoreCell = currentCell.NextSibling.NextSibling as Cell;

                    WordHelper.Write(scoreCell, font, GetPeriodCredit(domainScore.Period, domainScore.Credit));
                    //scoreCell = scoreCell.NextSibling as Cell;
                    //WordHelper.Write(scoreCell, font, "" + domainScore.Score);
                    scoreCell = scoreCell.NextSibling as Cell;
                    WordHelper.Write(scoreCell, font, (domainScore.Score.HasValue ? _degreeMapper.GetDegreeByScore(domainScore.Score.Value) : ""));

                    if (!_domainText.ContainsKey(domain))
                    {
                        _domainText.Add(domain, domainScore.Text);
                    }

                    if (rowCount <= 0)
                    {
                        break;
                    }
                    currentCell = WordHelper.GetMoveDownCell(currentCell, 1);

                    #endregion
                }
                else
                {
                    #region 詳列科目成績
                    if (!domainSubjects.ContainsKey(domain))
                    {
                        continue;
                    }

                    Cell subjectCell  = currentCell;
                    int  subjectCount = 0;
                    foreach (SubjectScore subjectScore in domainSubjects[domain])
                    {
                        rowCount--;
                        subjectCount++;

                        Cell temp = subjectCell.NextSibling as Cell;
                        WordHelper.Write(temp, font, subjectScore.Subject);
                        temp = temp.NextSibling as Cell;
                        WordHelper.Write(temp, font, GetPeriodCredit(subjectScore.Period, subjectScore.Credit));
                        //temp = temp.NextSibling as Cell;
                        //WordHelper.Write(temp, font, "" + subjectScore.Score);
                        temp = temp.NextSibling as Cell;
                        WordHelper.Write(temp, font, (subjectScore.Score.HasValue ? _degreeMapper.GetDegreeByScore(subjectScore.Score.Value) : ""));

                        if (!_domainText.ContainsKey(subjectScore.Subject))
                        {
                            _domainText.Add(subjectScore.Subject, subjectScore.Text);
                        }

                        if (rowCount <= 0)
                        {
                            break;
                        }
                        subjectCell = WordHelper.GetMoveDownCell(subjectCell, 1);
                    }
                    if (subjectCount > 1)
                    {
                        WordHelper.MergeVerticalCell(currentCell, subjectCount);
                    }
                    WordHelper.Write(currentCell, font, string.IsNullOrEmpty(domain) ? "彈性課程" : domain);

                    if (rowCount <= 0)
                    {
                        break;
                    }
                    currentCell = WordHelper.GetMoveDownCell(currentCell, subjectCount);
                    #endregion
                }
            }

            currentCell = startCell;
            string lastGroup = string.Empty;
            while (currentCell != endCell)
            {
                string currentGroup = currentCell.ToTxt().Replace("\r\n", "");
                if (currentGroup == lastGroup && !string.IsNullOrEmpty(lastGroup))
                {
                    currentCell.CellFormat.VerticalMerge = CellMerge.Previous;
                }
                lastGroup   = currentGroup;
                currentCell = WordHelper.GetMoveDownCell(currentCell, 1);
                if (currentCell == null)
                {
                    break;
                }
            }
            #endregion

            #region 填學習領域文字描述
            builder.MoveToMergeField("文字描述");
            Cell      textCell = builder.CurrentParagraph.ParentNode as Cell;
            Paragraph para     = (Paragraph)textCell.GetChild(NodeType.Paragraph, 0, true);
            font = para.ParagraphBreakFont;
            textCell.Paragraphs.Clear();
            foreach (string header in _domainText.Keys)
            {
                if (string.IsNullOrEmpty(_domainText[header]))
                {
                    continue;
                }

                textCell.Paragraphs.Add(new Paragraph(doc));

                Run run1 = new Run(doc);
                run1.Font.Name = font.Name;
                run1.Font.Size = font.Size;
                run1.Font.Bold = true;
                run1.Text      = header + ":";
                Run run2 = new Run(doc);
                run2.Font.Name = font.Name;
                run2.Font.Size = font.Size;
                run2.Text      = _domainText[header];

                textCell.LastParagraph.Runs.Add(run1);
                textCell.LastParagraph.Runs.Add(run2);
            }
            #endregion
        }
        public void Should_ReturnTrue_When_WordHasMinLetters()
        {
            var result = WordHelper.CheckInput(new string[] { "as", "tu" });

            Assert.AreEqual(result, true);
        }
示例#4
0
        private void ProcessAttendance(List <AutoSummaryRecord> autoSummaryList)
        {
            #region 定位,產生Row
            _builder.MoveToMergeField("缺曠");
            Cell  currentCell = _builder.CurrentParagraph.ParentNode as Cell;
            Row   currentRow  = currentCell.ParentRow;
            Table table       = currentRow.ParentTable;

            if (_types.Count <= 0)
            {
                currentRow.Remove();
                return;
            }
            else
            {
                int rowCount = 0;
                foreach (string type in _types.Keys)
                {
                    rowCount += _types[type].Count;
                }

                int insertIndex = table.Rows.IndexOf(currentRow) + 1;
                for (int i = 1; i < rowCount; i++)
                {
                    table.Rows.Insert(insertIndex, currentRow.Clone(true));
                }
            }
            #endregion

            string postfix = "節數";

            #region 寫入缺曠資料
            Dictionary <string, Dictionary <string, ValueItemRow> > items = new Dictionary <string, Dictionary <string, ValueItemRow> >();

            foreach (string type in _types.Keys)
            {
                if (!items.ContainsKey(type))
                {
                    items.Add(type, new Dictionary <string, ValueItemRow>());
                }
                foreach (string name in _types[type])
                {
                    if (!items[type].ContainsKey(name + postfix))
                    {
                        items[type].Add(name + postfix, new ValueItemRow(name + postfix));
                    }
                }
            }

            foreach (AutoSummaryRecord record in autoSummaryList)
            {
                SemesterData semester = new SemesterData("" + record.SchoolYear, "" + record.Semester);

                foreach (AbsenceCountRecord absence in record.AbsenceCounts)
                {
                    if (items.ContainsKey(absence.PeriodType) && items[absence.PeriodType].ContainsKey(absence.Name + postfix))
                    {
                        items[absence.PeriodType][absence.Name + postfix].Add(semester, absence.Count);
                    }
                }
            }

            Cell cell = currentCell;

            foreach (string type in items.Keys)
            {
                int count = items[type].Count;
                WordHelper.MergeVerticalCell(cell, count);

                WordHelper.Write(cell, type, _builder);

                Cell itemCell = WordHelper.GetMoveRightCell(cell, 1);
                foreach (ValueItemRow row in items[type].Values)
                {
                    WriteValueItemRow(itemCell, row);
                    itemCell = WordHelper.GetMoveDownCell(itemCell, 1);
                    if (itemCell == null)
                    {
                        break;
                    }
                }

                Cell tempCell = WordHelper.GetMoveDownCell(cell, count);
                if (tempCell == null)
                {
                    break;
                }
                cell = tempCell;
            }
            #endregion
        }
示例#5
0
        private void ProcessMoralScore(List <AutoSummaryRecord> autoSummaryList)
        {
            Dictionary <string, MoralItemRow> items = new Dictionary <string, MoralItemRow>();

            //團體活動
            MoralItemRow groupActivityRow = null;

            //公共服務
            MoralItemRow publicServiceRow = null;

            //校內外特殊表現
            MoralItemRow schoolSpecialRow = null;
            //具體建議
            MoralItemRow recommendRow = null;

            #region 建立適合列印的資料結構
            foreach (AutoSummaryRecord asRecord in autoSummaryList)
            {
                if (asRecord.MoralScore == null)
                {
                    continue;
                }
                JHMoralScoreRecord record   = asRecord.MoralScore;
                SemesterData       semester = new SemesterData("" + record.SchoolYear, "" + record.Semester);

                XmlElement dailyBehavior = (XmlElement)record.TextScore.SelectSingleNode("DailyBehavior");
                if (dailyBehavior != null)
                {
                    foreach (XmlElement item in dailyBehavior.SelectNodes("Item"))
                    {
                        string name   = item.GetAttribute("Name");
                        string index  = item.GetAttribute("Index");
                        string degree = item.GetAttribute("Degree");

                        string[] lines = index.Split(new string[] { ";", ";" }, StringSplitOptions.RemoveEmptyEntries);

                        if (!items.ContainsKey(name))
                        {
                            items.Add(name, new MoralItemRow(lines));
                        }

                        items[name].Add(semester, degree);
                    }
                }

                XmlElement dailyLifeRecommend = (XmlElement)record.TextScore.SelectSingleNode("DailyLifeRecommend");
                if (dailyLifeRecommend != null)
                {
                    string GroupName = "";
                    if (Utility.MorItemDict.ContainsKey("DailyLifeRecommend"))
                    {
                        GroupName = Utility.MorItemDict["DailyLifeRecommend"];
                    }

                    if (recommendRow == null)
                    {
                        recommendRow = new MoralItemRow(new string[] { GroupName });
                    }
                    recommendRow.Add(semester, dailyLifeRecommend.GetAttribute("Description"));
                }

                // 團體活動
                XmlElement groupActivity = (XmlElement)record.TextScore.SelectSingleNode("GroupActivity");
                if (groupActivity != null)
                {
                    string GroupName = "";
                    if (Utility.MorItemDict.ContainsKey("GroupActivity"))
                    {
                        GroupName = Utility.MorItemDict["GroupActivity"];
                    }

                    if (groupActivityRow == null)
                    {
                        groupActivityRow = new MoralItemRow(new string[] { GroupName });
                    }

                    string text = string.Empty;

                    foreach (XmlElement item in groupActivity.SelectNodes("Item"))
                    {
                        string degree = item.GetAttribute("Degree");
                        string desc   = item.GetAttribute("Description");
                        string name   = item.GetAttribute("Name");

                        if (string.IsNullOrEmpty(degree) && string.IsNullOrEmpty(desc))
                        {
                            continue;
                        }

                        string line = name + ":" + (string.IsNullOrEmpty(degree) ? "" : degree + "/") + (string.IsNullOrEmpty(desc) ? "" : desc);
                        if (line.EndsWith("/"))
                        {
                            line = line.Substring(0, line.Length - 1);
                        }
                        text += line;
                    }

                    // 加入社團
                    if (_assnScoreCache.ContainsKey(record.RefStudentID))
                    {
                        string sc = record.SchoolYear.ToString();
                        string ss = record.Semester.ToString();
                        foreach (AssnScore asc in _assnScoreCache[record.RefStudentID])
                        {
                            if (asc.SchoolYear == sc && asc.Semester == ss)
                            {
                                text += "社團活動:" + asc.Score + "," + asc.Effort + "/" + asc.Text;
                            }
                        }
                    }
                    groupActivityRow.Add(semester, text);
                }



                XmlElement publicService = (XmlElement)record.TextScore.SelectSingleNode("PublicService");
                if (publicService != null)
                {
                    string GroupName = "";
                    if (Utility.MorItemDict.ContainsKey("PublicService"))
                    {
                        GroupName = Utility.MorItemDict["PublicService"];
                    }

                    if (publicServiceRow == null)
                    {
                        publicServiceRow = new MoralItemRow(new string[] { GroupName });
                    }

                    string text = string.Empty;

                    foreach (XmlElement item in publicService.SelectNodes("Item"))
                    {
                        string degree = item.GetAttribute("Degree");
                        string desc   = item.GetAttribute("Description");
                        string name   = item.GetAttribute("Name");

                        if (string.IsNullOrEmpty(degree) && string.IsNullOrEmpty(desc))
                        {
                            continue;
                        }

                        string line = name + ":" + (string.IsNullOrEmpty(degree) ? "" : degree + "/") + (string.IsNullOrEmpty(desc) ? "" : desc);
                        if (line.EndsWith("/"))
                        {
                            line = line.Substring(0, line.Length - 1);
                        }
                        text += line;
                    }

                    publicServiceRow.Add(semester, text);
                }

                XmlElement schoolSpecial = (XmlElement)record.TextScore.SelectSingleNode("SchoolSpecial");
                if (schoolSpecial != null)
                {
                    string GroupName = "";
                    if (Utility.MorItemDict.ContainsKey("SchoolSpecial"))
                    {
                        GroupName = Utility.MorItemDict["SchoolSpecial"];
                    }

                    if (schoolSpecialRow == null)
                    {
                        schoolSpecialRow = new MoralItemRow(new string[] { GroupName });
                    }

                    string text = string.Empty;

                    foreach (XmlElement item in schoolSpecial.SelectNodes("Item"))
                    {
                        string degree = item.GetAttribute("Degree");
                        string desc   = item.GetAttribute("Description");
                        string name   = item.GetAttribute("Name");

                        if (string.IsNullOrEmpty(degree) && string.IsNullOrEmpty(desc))
                        {
                            continue;
                        }

                        string line = name + ":" + (string.IsNullOrEmpty(degree) ? "" : degree + "/") + (string.IsNullOrEmpty(desc) ? "" : desc);
                        if (line.EndsWith("/"))
                        {
                            line = line.Substring(0, line.Length - 1);
                        }
                        text += line;
                    }

                    schoolSpecialRow.Add(semester, text);
                }
            }
            #endregion

            #region 定位,產生Row
            _builder.MoveToMergeField("日常行為表現");
            Cell  currentCell = _builder.CurrentParagraph.ParentNode as Cell;
            Row   currentRow  = currentCell.ParentRow;
            Table table       = currentRow.ParentTable;

            int rowCount    = items.Count;
            int insertIndex = table.Rows.IndexOf(currentRow) + 1;
            for (int i = 1; i < rowCount; i++)
            {
                table.Rows.Insert(insertIndex, currentRow.Clone(true));
            }
            #endregion

            #region 寫入日常行為表現
            Cell cell = currentCell;

            foreach (string key in items.Keys)
            {
                WordHelper.Write(cell, key, _builder);

                Cell indexCell = WordHelper.GetMoveRightCell(cell, 1);
                WriteMoralItemRow(indexCell, items[key]);

                cell = WordHelper.GetMoveDownCell(cell, 1);
            }
            #endregion

            #region 寫入團體活動表現
            _builder.MoveToMergeField("團體活動");
            if (groupActivityRow != null && groupActivityRow.Items.Count > 0)
            {
                currentCell = _builder.CurrentParagraph.ParentNode as Cell;
                WriteMoralItemRow(currentCell, groupActivityRow);
                if (currentCell.Paragraphs.Count > 0)
                {
                    currentCell.Paragraphs[0].ParagraphFormat.Alignment = ParagraphAlignment.Center;
                }
            }
            else
            {
                (_builder.CurrentParagraph.ParentNode as Cell).ParentRow.Remove();
            }
            #endregion

            #region 寫入公共服務表現
            _builder.MoveToMergeField("公共服務");
            if (publicServiceRow != null && publicServiceRow.Items.Count > 0)
            {
                currentCell = _builder.CurrentParagraph.ParentNode as Cell;
                WriteMoralItemRow(currentCell, publicServiceRow);
                if (currentCell.Paragraphs.Count > 0)
                {
                    currentCell.Paragraphs[0].ParagraphFormat.Alignment = ParagraphAlignment.Center;
                }
            }
            else
            {
                (_builder.CurrentParagraph.ParentNode as Cell).ParentRow.Remove();
            }
            #endregion

            #region 寫入校內外特殊表現
            _builder.MoveToMergeField("校內外特殊");
            if (schoolSpecialRow != null && schoolSpecialRow.Items.Count > 0)
            {
                currentCell = _builder.CurrentParagraph.ParentNode as Cell;
                WriteMoralItemRow(currentCell, schoolSpecialRow);
                if (currentCell.Paragraphs.Count > 0)
                {
                    currentCell.Paragraphs[0].ParagraphFormat.Alignment = ParagraphAlignment.Center;
                }
            }
            else
            {
                (_builder.CurrentParagraph.ParentNode as Cell).ParentRow.Remove();
            }
            #endregion

            #region 寫入具體建議
            _builder.MoveToMergeField("具體建議");
            if (recommendRow != null && recommendRow.Items.Count > 0)
            {
                currentCell = _builder.CurrentParagraph.ParentNode as Cell;
                WriteMoralItemRow(currentCell, recommendRow);
                if (currentCell.Paragraphs.Count > 0)
                {
                    currentCell.Paragraphs[0].ParagraphFormat.Alignment = ParagraphAlignment.Center;
                }
            }
            else
            {
                (_builder.CurrentParagraph.ParentNode as Cell).ParentRow.Remove();
            }
            #endregion
        }
示例#6
0
        public void Writer(Document doc)
        {
            DocumentBuilder builder = new DocumentBuilder(doc);

            if (AutoSummaryRecord == null)
            {
                AutoSummaryRecord = new AutoSummaryRecord();
            }
            XmlElement summary   = (AutoSummaryRecord != null && AutoSummaryRecord.MoralScore != null) ? AutoSummaryRecord.MoralScore.Summary : K12.Data.XmlHelper.LoadXml("<Summary/>");
            XmlElement textScore = (AutoSummaryRecord != null && AutoSummaryRecord.MoralScore != null) ? AutoSummaryRecord.MoralScore.TextScore : K12.Data.XmlHelper.LoadXml("<TextScore/>");

            double width;
            double miniUnitWitdh;
            Table  table;
            Font   font;

            #region 日常生活表現評量

            #region 處理日常生活表現評量的名稱

            /* 日常生活表現評量的名稱key:
             *  日常行為表現
             *  其它表現
             *  日常生活表現具體建議
             *  團體活動表現
             *  公共服務表現
             *  校內外特殊表現
             */

            if (builder.MoveToMergeField("日常行為表現名稱"))
            {
                builder.Write(GetDLString("日常行為表現"));
            }

            //if ((XmlElement)textScore.SelectSingleNode("DailyBehavior") == null)
            //    ProcessItemNameIsNull(builder, "日常行為表現名稱", "日常行為表現");
            //else
            //{
            //    XmlElement xm = (XmlElement)textScore.SelectSingleNode("DailyBehavior");
            //    if (xm.GetAttribute("Name") == "")
            //        ProcessItemNameIsNull(builder, "日常行為表現名稱", "日常行為表現");
            //    else
            //        ProcessItemName(builder, "日常行為表現名稱", xm);
            //}


            if (Global.Params["Mode"] == "KaoHsiung")
            {
                #region 高雄
                if (builder.MoveToMergeField("團體活動表現名稱"))
                {
                    builder.Write(GetDLString("團體活動表現"));
                }
                //if ((XmlElement)textScore.SelectSingleNode("GroupActivity") == null)
                //    ProcessItemNameIsNull(builder, "團體活動表現名稱", "團體活動表現");
                //else
                //{
                //    XmlElement xm =(XmlElement)textScore.SelectSingleNode("GroupActivity");
                //    if(xm.GetAttribute("Name")=="")
                //        ProcessItemNameIsNull(builder, "團體活動表現名稱", "團體活動表現");
                //    else
                //        ProcessItemName(builder, "團體活動表現名稱", xm);
                //}

                if (builder.MoveToMergeField("公共服務表現名稱"))
                {
                    builder.Write(GetDLString("公共服務表現"));
                }
                //if ((XmlElement)textScore.SelectSingleNode("PublicService") == null)
                //    ProcessItemNameIsNull(builder, "公共服務表現名稱", "公共服務表現");
                //else
                //{
                //    XmlElement xm = (XmlElement)textScore.SelectSingleNode("PublicService");
                //    if (xm.GetAttribute("Name") == "")
                //        ProcessItemNameIsNull(builder, "公共服務表現名稱", "公共服務表現");
                //    else
                //        ProcessItemName(builder, "公共服務表現名稱",xm);
                //}
                if (builder.MoveToMergeField("校內外特殊表現名稱"))
                {
                    builder.Write(GetDLString("校內外特殊表現"));
                }
                //if ((XmlElement)textScore.SelectSingleNode("SchoolSpecial") == null)
                //    ProcessItemNameIsNull(builder, "校內外特殊表現名稱", "校內外特殊表現");
                //else
                //{
                //    XmlElement xm = (XmlElement)textScore.SelectSingleNode("SchoolSpecial");
                //    if (xm.GetAttribute("Name") == "")
                //        ProcessItemNameIsNull(builder, "校內外特殊表現名稱", "校內外特殊表現");
                //    else
                //        ProcessItemName(builder, "校內外特殊表現名稱", xm);
                //}

                if (builder.MoveToMergeField("日常生活表現具體建議名稱"))
                {
                    builder.Write(GetDLString("日常生活表現具體建議"));
                }
                //if ((XmlElement)textScore.SelectSingleNode("DailyLifeRecommend") == null)
                //    ProcessItemNameIsNull(builder, "日常生活表現具體建議名稱", "日常生活表現具體建議");
                //else
                //{
                //    XmlElement xm = (XmlElement)textScore.SelectSingleNode("DailyLifeRecommend");
                //    if (xm.GetAttribute("Name") == "")
                //        ProcessItemNameIsNull(builder, "日常生活表現具體建議名稱", "日常生活表現具體建議");
                //    else
                //        ProcessItemName(builder, "日常生活表現具體建議名稱", xm);
                //}

                #endregion
            }
            else
            {
                #region 新竹
                if (builder.MoveToMergeField("其他表現名稱"))
                {
                    builder.Write(GetDLString("其它表現"));
                }
                //if ((XmlElement)textScore.SelectSingleNode("OtherRecommend") == null)
                //    ProcessItemNameIsNull(builder, "其他表現名稱", "其他表現");
                //else
                //    ProcessItemName(builder, "其他表現名稱", (XmlElement)textScore.SelectSingleNode("OtherRecommend"));

                if (builder.MoveToMergeField("綜合評語名稱"))
                {
                    builder.Write(GetDLString("綜合評語"));
                }
                //if ((XmlElement)textScore.SelectSingleNode("DailyLifeRecommend") == null)
                //    ProcessItemNameIsNull(builder, "綜合評語名稱", "綜合評語");
                //else
                //    ProcessItemName(builder, "綜合評語名稱", (XmlElement)textScore.SelectSingleNode("DailyLifeRecommend"));
                #endregion
            }
            #endregion

            #region 處理日常生活表現評量的內容
            if (builder.MoveToMergeField("日常行為"))
            {
                font = builder.Font;
                Cell dailyBehaviorCell = builder.CurrentParagraph.ParentNode as Cell;
                if (Global.DLBehaviorConfigItemNameDict.ContainsKey("日常行為表現"))
                {
                    foreach (string itemName in Global.DLBehaviorConfigItemNameDict["日常行為表現"])
                    {
                        WordHelper.Write(dailyBehaviorCell, font, itemName);
                        bool hasDegree = false;
                        foreach (XmlElement item in textScore.SelectNodes("DailyBehavior/Item"))
                        {
                            if (itemName == item.GetAttribute("Name"))
                            {
                                if (dailyBehaviorCell.NextSibling == null)
                                {
                                    break;
                                }
                                WordHelper.Write(dailyBehaviorCell.NextSibling as Cell, font, item.GetAttribute("Degree"));
                                hasDegree = true;
                            }
                        }
                        if (hasDegree == false)
                        {
                            WordHelper.Write(dailyBehaviorCell.NextSibling as Cell, font, "");
                        }

                        dailyBehaviorCell = WordHelper.GetMoveDownCell(dailyBehaviorCell, 1);
                    }
                }
            }

            if (Global.Params["Mode"] == "KaoHsiung")
            {
                #region 高雄
                if (builder.MoveToMergeField("團體活動"))
                {
                    font = builder.Font;
                    Cell groupActivityCell = builder.CurrentParagraph.ParentNode as Cell;

                    Paragraph para = (Paragraph)groupActivityCell.GetChild(NodeType.Paragraph, 0, true);
                    font = para.ParagraphBreakFont;
                    groupActivityCell.Paragraphs.RemoveAt(0);
                    if (Global.DLBehaviorConfigItemNameDict.ContainsKey("團體活動表現"))
                    {
                        foreach (string itemName in Global.DLBehaviorConfigItemNameDict["團體活動表現"])
                        {
                            groupActivityCell.Paragraphs.Add(new Paragraph(doc));
                            Run run1 = new Run(doc);
                            run1.Font.Name = font.Name;
                            run1.Font.Size = font.Size;
                            run1.Font.Bold = true;
                            run1.Text      = itemName + ":";
                            groupActivityCell.LastParagraph.Runs.Add(run1);

                            Run run2 = new Run(doc);
                            run2.Font.Name = font.Name;
                            run2.Font.Size = font.Size;

                            Run run3h = new Run(doc);
                            Run run3  = new Run(doc);

                            foreach (XmlElement item in textScore.SelectNodes("GroupActivity/Item"))
                            {
                                if (itemName == item.GetAttribute("Name"))
                                {
                                    // 是否有文字描述
                                    bool hasText = false;
                                    if (!string.IsNullOrEmpty(item.GetAttribute("Description")))
                                    {
                                        hasText = true;
                                    }

                                    if (string.IsNullOrEmpty(item.GetAttribute("Degree")))
                                    {
                                        run2.Text = item.GetAttribute("Degree");
                                    }
                                    else
                                    {
                                        run2.Text = item.GetAttribute("Degree") + "。";
                                    }
                                    if (hasText)
                                    {
                                        run3h.Font.Name = font.Name;
                                        run3h.Font.Size = font.Size;
                                        run3h.Font.Bold = true;
                                        run3h.Text      = item.GetAttribute("Name") + ":";
                                        run3.Font.Name  = font.Name;
                                        run3.Font.Size  = font.Size;
                                        run3.Text       = item.GetAttribute("Description") + "。";
                                    }
                                    else
                                    {
                                        run3h.Font.Name = font.Name;
                                        run3h.Font.Size = font.Size;
                                        run3h.Text      = "";
                                        run3.Font.Name  = font.Name;
                                        run3.Font.Size  = font.Size;
                                        run3.Text       = "";
                                    }
                                }
                            }
                            groupActivityCell.LastParagraph.Runs.Add(run2);
                            groupActivityCell.LastParagraph.Runs.Add(run3h);
                            groupActivityCell.LastParagraph.Runs.Add(run3);
                        }
                    }
                }

                if (builder.MoveToMergeField("公共服務"))
                {
                    font = builder.Font;
                    Cell      publicServiceCell = builder.CurrentParagraph.ParentNode as Cell;
                    Paragraph para = (Paragraph)publicServiceCell.GetChild(NodeType.Paragraph, 0, true);
                    font = para.ParagraphBreakFont;
                    publicServiceCell.Paragraphs.Clear();

                    if (Global.DLBehaviorConfigItemNameDict.ContainsKey("公共服務表現"))
                    {
                        foreach (string itemName in Global.DLBehaviorConfigItemNameDict["公共服務表現"])
                        {
                            publicServiceCell.Paragraphs.Add(new Paragraph(doc));
                            Run run1 = new Run(doc);
                            run1.Font.Name = font.Name;
                            run1.Font.Size = font.Size;
                            run1.Font.Bold = true;
                            run1.Text      = itemName + ":";
                            bool hasDescription = false;
                            publicServiceCell.LastParagraph.Runs.Add(run1);

                            foreach (XmlElement item in textScore.SelectNodes("PublicService/Item"))
                            {
                                if (itemName == item.GetAttribute("Name"))
                                {
                                    Run run2 = new Run(doc);
                                    run2.Font.Name = font.Name;
                                    run2.Font.Size = font.Size;
                                    run2.Text      = item.GetAttribute("Description");
                                    publicServiceCell.LastParagraph.Runs.Add(run2);
                                    hasDescription = true;
                                }
                            }

                            if (hasDescription == false)
                            {
                                Run run2 = new Run(doc);
                                run2.Font.Name = font.Name;
                                run2.Font.Size = font.Size;
                                run2.Text      = "";
                                publicServiceCell.LastParagraph.Runs.Add(run2);
                            }
                        }
                    }
                }

                if (builder.MoveToMergeField("校內外特殊"))
                {
                    font = builder.Font;
                    Cell      schoolSpecialCell = builder.CurrentParagraph.ParentNode as Cell;
                    Paragraph para = (Paragraph)schoolSpecialCell.GetChild(NodeType.Paragraph, 0, true);
                    font = para.ParagraphBreakFont;
                    schoolSpecialCell.Paragraphs.Clear();

                    if (Global.DLBehaviorConfigItemNameDict.ContainsKey("校內外特殊表現"))
                    {
                        foreach (string itemName in Global.DLBehaviorConfigItemNameDict["校內外特殊表現"])
                        {
                            schoolSpecialCell.Paragraphs.Add(new Paragraph(doc));
                            Run run1 = new Run(doc);
                            run1.Font.Name = font.Name;
                            run1.Font.Size = font.Size;
                            run1.Font.Bold = true;
                            run1.Text      = itemName + ":";
                            schoolSpecialCell.LastParagraph.Runs.Add(run1);
                            bool hasDescription = false;
                            foreach (XmlElement item in textScore.SelectNodes("SchoolSpecial/Item"))
                            {
                                if (itemName == item.GetAttribute("Name"))
                                {
                                    Run run2 = new Run(doc);
                                    run2.Font.Name = font.Name;
                                    run2.Font.Size = font.Size;
                                    run2.Text      = item.GetAttribute("Description");
                                    schoolSpecialCell.LastParagraph.Runs.Add(run2);
                                    hasDescription = true;
                                }
                            }

                            if (hasDescription == false)
                            {
                                Run run2 = new Run(doc);
                                run2.Font.Name = font.Name;
                                run2.Font.Size = font.Size;
                                run2.Text      = "";
                                schoolSpecialCell.LastParagraph.Runs.Add(run2);
                            }
                        }
                    }
                }

                if (builder.MoveToMergeField("具體建議"))
                {
                    font = builder.Font;
                    Cell       dailyLifeRecommendCell  = builder.CurrentParagraph.ParentNode as Cell;
                    XmlElement dailyLifeRecommend      = (XmlElement)textScore.SelectSingleNode("DailyLifeRecommend");
                    string     dailyLifeRecommendValue = string.Empty;
                    if (dailyLifeRecommend != null)
                    {
                        dailyLifeRecommendValue = dailyLifeRecommend.GetAttribute("Description");
                    }

                    Paragraph para = (Paragraph)dailyLifeRecommendCell.GetChild(NodeType.Paragraph, 0, true);
                    font = para.ParagraphBreakFont;
                    dailyLifeRecommendCell.Paragraphs.Clear();
                    dailyLifeRecommendCell.Paragraphs.Add(new Paragraph(doc));
                    Run run = new Run(doc);
                    run.Font.Name = font.Name;
                    run.Font.Size = font.Size;
                    run.Text      = dailyLifeRecommendValue;

                    dailyLifeRecommendCell.LastParagraph.Runs.Add(run);
                }
                #endregion
            }
            else
            {
                #region 新竹
                if (builder.MoveToMergeField("其他表現"))
                {
                    font = builder.Font;
                    Cell       otherRecommendCell  = builder.CurrentParagraph.ParentNode as Cell;
                    XmlElement otherRecommend      = (XmlElement)textScore.SelectSingleNode("OtherRecommend");
                    string     otherRecommendValue = string.Empty;
                    if (otherRecommend != null)
                    {
                        otherRecommendValue = otherRecommend.GetAttribute("Description");
                    }

                    Paragraph para = (Paragraph)otherRecommendCell.GetChild(NodeType.Paragraph, 0, true);
                    font = para.ParagraphBreakFont;
                    otherRecommendCell.Paragraphs.Clear();
                    otherRecommendCell.Paragraphs.Add(new Paragraph(doc));
                    Run otherRecommendRun = new Run(doc);
                    otherRecommendRun.Font.Name = font.Name;
                    otherRecommendRun.Font.Size = font.Size;
                    otherRecommendRun.Text      = otherRecommendValue;
                    otherRecommendCell.LastParagraph.Runs.Add(otherRecommendRun);
                }

                if (builder.MoveToMergeField("綜合評語"))
                {
                    font = builder.Font;
                    Cell       dailyLifeRecommendCell  = builder.CurrentParagraph.ParentNode as Cell;
                    XmlElement dailyLifeRecommend      = (XmlElement)textScore.SelectSingleNode("DailyLifeRecommend");
                    string     dailyLifeRecommendValue = string.Empty;
                    if (dailyLifeRecommend != null)
                    {
                        dailyLifeRecommendValue = dailyLifeRecommend.GetAttribute("Description");
                    }

                    Paragraph para = (Paragraph)dailyLifeRecommendCell.GetChild(NodeType.Paragraph, 0, true);
                    font = para.ParagraphBreakFont;
                    dailyLifeRecommendCell.Paragraphs.Clear();
                    dailyLifeRecommendCell.Paragraphs.Add(new Paragraph(doc));
                    Run dailyLifeRecommendRun = new Run(doc);
                    dailyLifeRecommendRun.Font.Name = font.Name;
                    dailyLifeRecommendRun.Font.Size = font.Size;
                    dailyLifeRecommendRun.Text      = dailyLifeRecommendValue;
                    dailyLifeRecommendCell.LastParagraph.Runs.Add(dailyLifeRecommendRun);
                }
                #endregion
            }
            #endregion

            #region TextScore XML格式參考
            //<DailyBehavior Name="日常行為表現">
            //    <Item Degree="大部份符合" Index="抽屜乾淨" Name="愛整潔"/>
            //    <Item Degree="尚再努力" Index="懂得向老師,學長敬禮" Name="有禮貌"/>
            //    <Item Degree="大部份符合" Index="自習時間能夠安靜自習" Name="守秩序"/>
            //    <Item Degree="尚再努力" Index="打掃時間,徹底整理自己打掃範圍" Name="責任心"/>
            //    <Item Degree="需再努力" Index="不亂丟垃圾" Name="公德心"/>
            //    <Item Degree="大部份符合" Index="懂得關心同學朋友" Name="友愛關懷"/>
            //    <Item Degree="大部份符合" Index="團體活動能夠遵守相關規定" Name="團隊合作"/>
            //</DailyBehavior>
            //<GroupActivity Name="團體活動表現">
            //    <Item Degree="表現良好" Description="社團" Name="社團活動"/>
            //    <Item Degree="表現優異" Description="學校" Name="學校活動"/>
            //    <Item Degree="有待改進" Description="自治" Name="自治活動"/>
            //    <Item Degree="需在加油" Description="班級" Name="班級活動"/>
            //</GroupActivity>
            //<PublicService Name="公共服務表現">
            //    <Item Description="校內" Name="校內服務"/>
            //    <Item Description="社區" Name="社區服務"/>
            //</PublicService>
            //<SchoolSpecial Name="校內外特殊表現">
            //    <Item Description="這麼特殊" Name="校外特殊表現"/>
            //    <Item Description="又是校內" Name="校內特殊表現"/>
            //</SchoolSpecial>
            //<DailyLifeRecommend Description="我錯了" Name="日常生活表現具體建議"/>
            #endregion

            #endregion

            #region 缺曠
            //<AttendanceStatistics>
            //    <Absence Count="4" Name="公假" PeriodType="一般"/>
            //    <Absence Count="4" Name="曠課" PeriodType="一般"/>
            //    <Absence Count="4" Name="凹假" PeriodType="一般"/>
            //</AttendanceStatistics>

            builder.MoveToMergeField("缺曠");

            if (_types.Count > 0)
            {
                Dictionary <string, string> attendance = new Dictionary <string, string>();
                foreach (AbsenceCountRecord absence in AutoSummaryRecord.AbsenceCounts)
                {
                    string key = GetKey(absence.PeriodType, absence.Name);
                    if (!attendance.ContainsKey(key))
                    {
                        attendance.Add(key, "" + absence.Count);
                    }
                }

                double total = 0;
                foreach (List <string> list in _types.Values)
                {
                    total += list.Count;
                }

                Cell attendanceCell = builder.CurrentParagraph.ParentNode as Cell;
                width         = attendanceCell.CellFormat.Width;
                miniUnitWitdh = width / total;

                table = builder.StartTable();
                builder.RowFormat.HeightRule = HeightRule.Exactly;
                builder.RowFormat.Height     = 17.5;

                foreach (string type in _types.Keys)
                {
                    builder.InsertCell().CellFormat.Width = miniUnitWitdh * _types[type].Count;
                    builder.Write(type);
                }
                builder.EndRow();

                foreach (string type in _types.Keys)
                {
                    foreach (string item in _types[type])
                    {
                        builder.InsertCell().CellFormat.Width = miniUnitWitdh;
                        builder.Write(item);
                    }
                }
                builder.EndRow();

                foreach (string type in _types.Keys)
                {
                    foreach (string item in _types[type])
                    {
                        builder.InsertCell().CellFormat.Width = miniUnitWitdh;
                        string key   = GetKey(type, item);
                        string value = attendance.ContainsKey(key) ? attendance[key] : "0";
                        builder.Write(value);
                    }
                }
                builder.EndRow();
                builder.EndTable();

                //去除表格四邊的線
                foreach (Cell c in table.FirstRow.Cells)
                {
                    c.CellFormat.Borders.Top.LineStyle = LineStyle.None;
                }

                foreach (Cell c in table.LastRow.Cells)
                {
                    c.CellFormat.Borders.Bottom.LineStyle = LineStyle.None;
                }

                foreach (Row r in table.Rows)
                {
                    r.FirstCell.CellFormat.Borders.Left.LineStyle = LineStyle.None;
                    r.LastCell.CellFormat.Borders.Right.LineStyle = LineStyle.None;
                }
            }
            #endregion

            #region 獎懲
            //<DisciplineStatistics>
            //    <Merit A="1" B="0" C="0"/>
            //    <Demerit A="12" B="12" C="14"/>
            //</DisciplineStatistics>

            Dictionary <string, string> discipline = new Dictionary <string, string>();
            discipline.Add("大功", "" + AutoSummaryRecord.MeritA);
            discipline.Add("小功", "" + AutoSummaryRecord.MeritB);
            discipline.Add("嘉獎", "" + AutoSummaryRecord.MeritC);
            discipline.Add("大過", "" + AutoSummaryRecord.DemeritA);
            discipline.Add("小過", "" + AutoSummaryRecord.DemeritB);
            discipline.Add("警告", "" + AutoSummaryRecord.DemeritC);

            builder.MoveToMergeField("獎懲");

            Cell disciplineCell = builder.CurrentParagraph.ParentNode as Cell;
            width         = disciplineCell.CellFormat.Width;
            miniUnitWitdh = width / 6f;

            table = builder.StartTable();
            builder.RowFormat.HeightRule = HeightRule.Exactly;
            builder.RowFormat.Height     = 17.5;

            foreach (string key in discipline.Keys)
            {
                builder.InsertCell().CellFormat.Width = miniUnitWitdh;
                builder.Write(key);
            }
            builder.EndRow();

            foreach (string key in discipline.Keys)
            {
                builder.InsertCell().CellFormat.Width = miniUnitWitdh;
                string value = string.IsNullOrEmpty(discipline[key]) ? "0" : discipline[key];
                builder.Write(value);
            }
            builder.EndRow();
            builder.EndTable();

            //去除表格四邊的線
            foreach (Cell c in table.FirstRow.Cells)
            {
                c.CellFormat.Borders.Top.LineStyle = LineStyle.None;
            }

            foreach (Cell c in table.LastRow.Cells)
            {
                c.CellFormat.Borders.Bottom.LineStyle = LineStyle.None;
            }

            foreach (Row r in table.Rows)
            {
                r.FirstCell.CellFormat.Borders.Left.LineStyle = LineStyle.None;
                r.LastCell.CellFormat.Borders.Right.LineStyle = LineStyle.None;
            }
            #endregion
        }
示例#7
0
 public FileResult Create(string html)
 {
     return(File(WordHelper.HtmlToWord(html), "application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
 }
示例#8
0
        public ActionResult GetTextSegment(int projectId, int fileId)
        {
            JsonResult     jsonResult = new JsonResult();
            SegmentsResult sResult    = new SegmentsResult();

            if (User.Identity.IsAuthenticated && GetUserPermission(SessionUser.GetUserId(), projectId))
            {
                Thread thrGetText = new Thread(new ThreadStart(() =>
                {
                    try
                    {
                        TranslateModel translateModel = new TranslateModel();
                        Project project  = translateModel.GetProject(projectId);
                        ProjectFile file = translateModel.GetFile(projectId, fileId);
                        if (project != null && file != null)
                        {
                            sResult.FileName    = file.FileName;
                            sResult.ProjectName = project.Title;
                            string importFile   = Utility.GetRootPath() + Contanst.rootProject + "\\" + project.Title + "\\Imports\\" + file.FileName;
                            var extFile         = Path.GetExtension(importFile);
                            switch (extFile)
                            {
                            case ".xls":
                            case ".xlsx":
                                sResult.FileType = (int)FileTypes.EXCEL;
                                if (System.IO.File.Exists(importFile) && file.IsLoadText == true)
                                {
                                    List <TextSegment> lstPureTextSegment = translateModel.GetTextSegment(projectId, fileId);
                                    List <TextSegment> lstTextSegment     = new List <TextSegment>();
                                    foreach (var textSegment in lstPureTextSegment)
                                    {
                                        int iRow = textSegment.Row != null ? Convert.ToInt32(textSegment.Row) : -1;
                                        int iCol = textSegment.Col != null ? Convert.ToInt32(textSegment.Col) : -1;
                                        if (!(lstTextSegment.Any(a => a.TextSegment1 == textSegment.TextSegment1) && iRow != -1 && iCol != -1))                          //&& iRow != -1 && iCol != -1
                                        {
                                            lstTextSegment.Add(textSegment);
                                        }
                                    }

                                    sResult.ControllerResult.Value = lstTextSegment;
                                }
                                else if (System.IO.File.Exists(importFile) && file.IsLoadText == false)
                                {
                                    List <TextRead> segments = new List <TextRead>();
                                    List <TextRead> objects  = new List <TextRead>();
                                    using (var excel = new ExcelHelper(importFile, true))
                                    {
                                        segments = excel.GetTextSegment();
                                        objects  = excel.GetTextObject();
                                    }
                                    List <TextSegment> lstTextSegment = translateModel.GetTextSegment(projectId, fileId);
                                    List <TextRead> lstTextSegments   = new List <TextRead>();
                                    List <TextRead> lstTextObjects    = new List <TextRead>();
                                    foreach (var item in segments)
                                    {
                                        if (!lstTextSegment.Any(a => a.Row == item.Row && a.Col == item.Col && a.SheetName == item.SheetName && a.TextSegment1 == item.Value))
                                        {
                                            lstTextSegments.Add(item);
                                        }
                                    }
                                    foreach (var item in objects)
                                    {
                                        if (!lstTextSegment.Any(a => a.Row == item.Row && a.Col == item.Col && a.SheetName == item.SheetName && a.TextSegment1 == item.Value))
                                        {
                                            lstTextObjects.Add(item);
                                        }
                                    }
                                    var insertedTxt = translateModel.BatchInsert(lstTextSegments, fileId, projectId, (int)FileTypes.EXCEL, (int)TextSegmentType.TEXT);
                                    var insertedObj = translateModel.BatchInsert(lstTextObjects, fileId, projectId, (int)FileTypes.EXCEL, (int)TextSegmentType.OBJECT);
                                    translateModel.UpdateStatusFileTranslate(projectId, fileId, true);

                                    List <TextSegment> lstPureTextSegment = translateModel.GetTextSegment(projectId, fileId);
                                    List <TextSegment> lstSegments        = new List <TextSegment>();
                                    foreach (var textSegment in lstPureTextSegment)
                                    {
                                        int iRow = textSegment.Row != null ? Convert.ToInt32(textSegment.Row) : -1;
                                        int iCol = textSegment.Col != null ? Convert.ToInt32(textSegment.Col) : -1;
                                        if (!(lstSegments.Any(a => a.TextSegment1 == textSegment.TextSegment1) && iRow != -1 && iCol != -1))                         //&& iRow != -1 && iCol != -1
                                        {
                                            lstSegments.Add(textSegment);
                                        }
                                    }
                                    sResult.ControllerResult.Value = lstSegments;
                                }
                                else
                                {
                                    sResult.ControllerResult.IsSuccess = false;
                                    sResult.ControllerResult.Message   = "Physical file don't exist in server!";
                                }
                                break;

                            case ".doc":
                            case ".docx":
                                sResult.FileType = (int)FileTypes.WORD;
                                if (System.IO.File.Exists(importFile) && file.IsLoadText == true)
                                {
                                    List <TextSegment> lstTextSegment = translateModel.GetTextSegment(projectId, fileId);
                                    sResult.ControllerResult.Value    = lstTextSegment;
                                }
                                else if (System.IO.File.Exists(importFile) && file.IsLoadText == false)
                                {
                                    List <TextRead> segments = new List <TextRead>();
                                    List <TextRead> objects  = new List <TextRead>();
                                    using (var word = new WordHelper(importFile, true))
                                    {
                                        segments = word.GetTextSegmentInWord();
                                        objects  = word.GetTextObjectInWord();
                                    }
                                    List <TextSegment> lstTextSegment = translateModel.GetTextSegment(projectId, fileId);
                                    List <TextRead> lstTextSegments   = new List <TextRead>();
                                    List <TextRead> lstTextObjects    = new List <TextRead>();
                                    foreach (var item in segments)
                                    {
                                        if (!lstTextSegment.Any(a => a.TextSegment1 == item.Value && a.ParagraphsOrShapeIndex == item.ParagraphsOrShapeIndex))
                                        {
                                            lstTextSegments.Add(item);
                                        }
                                    }
                                    foreach (var item in objects)
                                    {
                                        if (!lstTextSegment.Any(a => a.TextSegment1 == item.Value && a.ParagraphsOrShapeIndex == item.ParagraphsOrShapeIndex))
                                        {
                                            lstTextObjects.Add(item);
                                        }
                                    }
                                    var insertedTxt = translateModel.BatchInsert(lstTextSegments, fileId, projectId, (int)FileTypes.WORD, (int)TextSegmentType.TEXT);
                                    var insertedObj = translateModel.BatchInsert(lstTextObjects, fileId, projectId, (int)FileTypes.WORD, (int)TextSegmentType.OBJECT);

                                    translateModel.UpdateStatusFileTranslate(projectId, fileId, true);
                                    List <TextSegment> lstPureTextSegment = translateModel.GetTextSegment(projectId, fileId);
                                    List <TextSegment> lstSegments        = new List <TextSegment>();
                                    foreach (var textSegment in lstPureTextSegment)
                                    {
                                        if (!(lstSegments.Any(a => a.TextSegment1 == textSegment.TextSegment1)))
                                        {
                                            lstSegments.Add(textSegment);
                                        }
                                    }
                                    sResult.ControllerResult.Value = lstSegments;
                                }
                                else
                                {
                                    sResult.ControllerResult.IsSuccess = false;
                                    sResult.ControllerResult.Message   = "Physical file don't exist in server!";
                                }
                                break;

                            case ".ppt":
                            case ".pptx":
                                sResult.FileType = (int)FileTypes.POWERPOINT;
                                if (System.IO.File.Exists(importFile) && file.IsLoadText == true)
                                {
                                    List <TextSegment> lstTextSegment = translateModel.GetTextSegment(projectId, fileId);
                                    sResult.ControllerResult.Value    = lstTextSegment;
                                }
                                else if (System.IO.File.Exists(importFile) && file.IsLoadText == false)
                                {
                                    List <TextRead> textSegments = new List <TextRead>();
                                    using (var powerpoint = new PowerPointHelper(importFile))
                                    {
                                        textSegments = powerpoint.GetTexts();
                                    }
                                    List <TextSegment> lstTextSegment = translateModel.GetTextSegment(projectId, fileId);
                                    List <TextRead> lstTextSegments   = new List <TextRead>();
                                    foreach (var item in textSegments)
                                    {
                                        if (!lstTextSegment.Any(a => a.TextSegment1 == item.Value && a.ParagraphsOrShapeIndex == item.ParagraphsOrShapeIndex))
                                        {
                                            lstTextSegments.Add(item);
                                        }
                                    }
                                    var insertedTxt = translateModel.BatchInsert(lstTextSegments, fileId, projectId, (int)FileTypes.WORD, (int)TextSegmentType.OBJECT);

                                    translateModel.UpdateStatusFileTranslate(projectId, fileId, true);
                                    List <TextSegment> lstPureTextSegment = translateModel.GetTextSegment(projectId, fileId);
                                    List <TextSegment> lstSegments        = new List <TextSegment>();
                                    foreach (var textSegment in lstPureTextSegment)
                                    {
                                        if (!(lstSegments.Any(a => a.TextSegment1 == textSegment.TextSegment1)))
                                        {
                                            lstSegments.Add(textSegment);
                                        }
                                    }
                                    sResult.ControllerResult.Value = lstSegments;
                                }
                                else
                                {
                                    sResult.ControllerResult.IsSuccess = false;
                                    sResult.ControllerResult.Message   = "Physical file don't exist in server!";
                                }
                                break;

                            case ".pdf":
                                //not yet complete
                                break;

                            default:
                                break;
                            }
                        }
                        else
                        {
                            sResult.ControllerResult.IsSuccess = false;
                            sResult.ControllerResult.Message   = "Project or file don't exist!";
                        }
                    }
                    catch (Exception ex)
                    {
                        sResult.ControllerResult.IsSuccess = false;
                        if (ex.Message == "Exception from HRESULT: 0x800AC472")
                        {
                            sResult.ControllerResult.Message = "Office driver is busying can't call to Interop service or office on server don't actived!";
                        }
                        else
                        {
                            sResult.ControllerResult.Message = ex.Message;
                        }
                    }
                    jsonResult = Json(sResult, JsonRequestBehavior.AllowGet);
                    jsonResult.MaxJsonLength = Int32.MaxValue;
                }));
                thrGetText.Start();
                thrGetText.Join();
            }
            else
            {
                sResult.ControllerResult.IsSuccess = false;
                sResult.ControllerResult.Message   = "User don't has permissions!";
            }
            return(jsonResult);
        }
示例#9
0
        public async Task <byte[]> GetWordDocument(Dictionary <string, string> data)
        {
            var path = Path.Combine(_pathProvider.MapPath(wordTemplatePath));

            return(await WordHelper.ReplaceInFile(path, data));
        }
示例#10
0
        public void TestMethod2()
        {
            var result = WordHelper.GenerateAddColumnSql("BasGoodsDetail", "BusinessFlag", "int", "业务类型,0:普通商品,1:拍卖商品", true);

            Console.WriteLine(result);
        }
示例#11
0
        public ActionResult BuildExportFile(int projectId, int fileId)
        {
            ControllerResult cResult    = new ControllerResult();
            JsonResult       jsonResult = new JsonResult();

            if (User.Identity.IsAuthenticated && GetUserPermission(SessionUser.GetUserId(), projectId))
            {
                Thread thrGetText = new Thread(new ThreadStart(() =>
                {
                    #region "build file export"
                    try
                    {
                        TranslateModel translateModel = new TranslateModel();
                        Project project  = translateModel.GetProject(projectId);
                        ProjectFile file = translateModel.GetFile(projectId, fileId);
                        if (project != null && file != null)
                        {
                            string rootPath   = Utility.GetRootPath();
                            string importPath = rootPath + Contanst.rootProject + "\\" + project.Title + "\\Imports";
                            string exportPath = rootPath + Contanst.rootProject + "\\" + project.Title + "\\Exports";
                            if (Directory.Exists(exportPath))
                            {
                                Directory.CreateDirectory(exportPath);
                            }
                            string filePath = importPath + "\\" + file.FileName;
                            if (!System.IO.File.Exists(filePath))
                            {
                                throw new Exception("File don't exits!");
                            }
                            exportPath  = exportPath + "\\" + file.FileName;
                            var fileExt = Path.GetExtension(file.FileName);
                            if (fileExt == null)
                            {
                                throw new Exception("Extension file error");
                            }
                            string translatedFile = exportPath.Replace(fileExt, $"_Export{fileExt}");
                            string fileNameExport = Path.GetFileName(translatedFile);
                            try
                            {
                                int i = 1;
                                while (System.IO.File.Exists(translatedFile))
                                {
                                    translatedFile = exportPath.Replace(fileExt, $"(" + i + ")_Export" + fileExt);
                                    i++;
                                }
                                System.IO.File.Copy(filePath, translatedFile, true);
                            }
                            catch (Exception)
                            {
                                Random r       = new Random();
                                translatedFile = filePath.Replace(fileExt, $"_r" + r.Next(100, 999) + "_vn" + fileExt);
                                fileNameExport = Path.GetFileName(translatedFile);
                                System.IO.File.Copy(filePath, translatedFile, true);
                            }
                            switch (fileExt)
                            {
                            case ".xls":
                            case ".xlsx":
                                using (var excel = new ExcelHelper(translatedFile, false))
                                {
                                    try
                                    {
                                        List <TextSegment> lstTextSegment         = translateModel.GetTextSegment(projectId, fileId);
                                        List <TextSegment> lstTextSegmentNoExists = new List <TextSegment>();
                                        foreach (var item in lstTextSegment)
                                        {
                                            var textSegment = lstTextSegment.Where(a => !String.IsNullOrEmpty(a.TextSegment2) && a.TextSegment1 == item.TextSegment1 && String.IsNullOrEmpty(item.TextSegment2)).FirstOrDefault();
                                            if (textSegment != null)
                                            {
                                                lstTextSegmentNoExists.Add(new TextSegment()
                                                {
                                                    TextSegment1 = item.TextSegment1, TextSegment2 = textSegment.TextSegment2, Type = item.Type, Row = item.Row, Col = item.Col, SheetName = item.SheetName, IsSheetName = item.IsSheetName, SheetIndex = item.SheetIndex
                                                });
                                            }
                                            else if (!String.IsNullOrEmpty(item.TextSegment2))
                                            {
                                                lstTextSegmentNoExists.Add(new TextSegment()
                                                {
                                                    TextSegment1 = item.TextSegment1, TextSegment2 = item.TextSegment2, Type = item.Type, Row = item.Row, Col = item.Col, SheetName = item.SheetName, IsSheetName = item.IsSheetName, SheetIndex = item.SheetIndex
                                                });
                                            }
                                        }
                                        lstTextSegmentNoExists = lstTextSegmentNoExists.OrderByDescending(x => x.TextSegment1.Length).ToList();
                                        foreach (TextSegment itTextSegment in lstTextSegmentNoExists)
                                        {
                                            if (!string.IsNullOrEmpty(itTextSegment.TextSegment2))
                                            {
                                                if ((TextSegmentType)itTextSegment.Type == TextSegmentType.TEXT)
                                                {
                                                    excel.ReplaceText(itTextSegment.TextSegment1, itTextSegment.TextSegment2, Convert.ToInt32(itTextSegment.Row), Convert.ToInt32(itTextSegment.Col), itTextSegment.SheetName, Convert.ToBoolean(itTextSegment.IsSheetName), Convert.ToInt32(itTextSegment.SheetIndex));     // Replace all text segment in words
                                                }
                                                else
                                                {
                                                    excel.ReplaceObject(itTextSegment.TextSegment1, itTextSegment.TextSegment2);
                                                }
                                            }
                                        }
                                        excel.Save();
                                    }
                                    catch (Exception ex)
                                    {
                                        throw ex;
                                    }
                                }
                                break;

                            case ".doc":
                            case ".docx":
                                using (var word = new WordHelper(translatedFile))
                                {
                                    List <TextSegment> lstTextSegment         = translateModel.GetTextSegment(projectId, fileId);
                                    List <TextSegment> lstTextSegmentNoExists = new List <TextSegment>();
                                    foreach (var item in lstTextSegment)
                                    {
                                        var textSegment = lstTextSegment.Where(a => !String.IsNullOrEmpty(a.TextSegment2) && a.TextSegment1 == item.TextSegment1 && String.IsNullOrEmpty(item.TextSegment2)).FirstOrDefault();
                                        if (textSegment != null)
                                        {
                                            lstTextSegmentNoExists.Add(new TextSegment()
                                            {
                                                TextSegment1 = item.TextSegment1, TextSegment2 = textSegment.TextSegment2, Type = item.Type, Row = item.Row, Col = item.Col, SheetName = item.SheetName, IsSheetName = item.IsSheetName, SheetIndex = item.SheetIndex, ParagraphsOrShapeIndex = item.ParagraphsOrShapeIndex
                                            });
                                        }
                                        else if (!String.IsNullOrEmpty(item.TextSegment2))
                                        {
                                            lstTextSegmentNoExists.Add(new TextSegment()
                                            {
                                                TextSegment1 = item.TextSegment1, TextSegment2 = item.TextSegment2, Type = item.Type, Row = item.Row, Col = item.Col, SheetName = item.SheetName, IsSheetName = item.IsSheetName, SheetIndex = item.SheetIndex, ParagraphsOrShapeIndex = item.ParagraphsOrShapeIndex
                                            });
                                        }
                                    }
                                    lstTextSegmentNoExists = lstTextSegmentNoExists.OrderByDescending(x => x.TextSegment1.Length).ToList();
                                    foreach (TextSegment itTextSegment in lstTextSegmentNoExists)
                                    {
                                        if (!string.IsNullOrEmpty(itTextSegment.TextSegment2))
                                        {
                                            if ((TextSegmentType)itTextSegment.Type == TextSegmentType.TEXT)
                                            {
                                                word.ReplaceText(itTextSegment.TextSegment1, itTextSegment.TextSegment2, itTextSegment.ParagraphsOrShapeIndex);     // Replace all text segment in words
                                            }
                                            else
                                            {
                                                word.ReplaceObject(itTextSegment.TextSegment1, itTextSegment.TextSegment2, itTextSegment.ParagraphsOrShapeIndex);
                                            }
                                        }
                                    }
                                    word.Save();
                                }
                                break;

                            case ".ppt":
                            case ".pptx":
                                using (var powerpoint = new PowerPointHelper(translatedFile, false))
                                {
                                    List <TextSegment> lstTextSegment         = translateModel.GetTextSegment(projectId, fileId);
                                    List <TextSegment> lstTextSegmentNoExists = new List <TextSegment>();
                                    foreach (var item in lstTextSegment)
                                    {
                                        var textSegment = lstTextSegment.Where(a => !String.IsNullOrEmpty(a.TextSegment2) && a.TextSegment1 == item.TextSegment1 && String.IsNullOrEmpty(item.TextSegment2)).FirstOrDefault();
                                        if (textSegment != null)
                                        {
                                            lstTextSegmentNoExists.Add(new TextSegment()
                                            {
                                                TextSegment1 = item.TextSegment1, TextSegment2 = textSegment.TextSegment2, Type = item.Type, Row = item.Row, Col = item.Col, SheetName = item.SheetName, IsSheetName = item.IsSheetName, SheetIndex = item.SheetIndex, ParagraphsOrShapeIndex = item.ParagraphsOrShapeIndex
                                            });
                                        }
                                        else if (!String.IsNullOrEmpty(item.TextSegment2))
                                        {
                                            lstTextSegmentNoExists.Add(new TextSegment()
                                            {
                                                TextSegment1 = item.TextSegment1, TextSegment2 = item.TextSegment2, Type = item.Type, Row = item.Row, Col = item.Col, SheetName = item.SheetName, IsSheetName = item.IsSheetName, SheetIndex = item.SheetIndex, ParagraphsOrShapeIndex = item.ParagraphsOrShapeIndex
                                            });
                                        }
                                    }
                                    lstTextSegmentNoExists = lstTextSegmentNoExists.OrderByDescending(x => x.TextSegment1.Length).ToList();
                                    foreach (TextSegment itTextSegment in lstTextSegmentNoExists)
                                    {
                                        if (!string.IsNullOrEmpty(itTextSegment.TextSegment2))
                                        {
                                            powerpoint.ReplaceObject(itTextSegment.TextSegment1, itTextSegment.TextSegment2, itTextSegment.ParagraphsOrShapeIndex);
                                        }
                                    }
                                    powerpoint.Save();
                                }
                                break;

                            case ".pdf":

                                break;

                            default:
                                break;
                            }
                            cResult.IsSuccess = true;
                            cResult.Value     = Path.GetFileName(translatedFile);
                        }
                        else
                        {
                            cResult.IsSuccess = false;
                            cResult.Message   = "Project or file had deleted or don't exits!";
                        }
                    }
                    catch (Exception ex)
                    {
                        cResult.IsSuccess = false;
                        cResult.Message   = "Build export file error!";
                    }
                    #endregion
                }));
                thrGetText.Start();
                thrGetText.Join();
            }
            else
            {
                cResult.IsSuccess = false;
                cResult.Message   = "User don't has permissions!";
            }
            return(Json(cResult));
        }
 CommonWordsController()
 {
     this.wordHelper = new WordHelper();
 }
示例#13
0
 static IEnumerable <Word> GetWordsOfLanguage(WordHelper helper, Language language)
 {
     return(from g in helper.GetWords() where g.LanguageId == language.Id select g);
 }
示例#14
0
 static void AddWord(WordHelper helper, Word word)
 {
     helper.AddEntity(word);
 }
示例#15
0
        //生成预报告
        private void btnProduce_ItemClick(object sender, ItemClickEventArgs e)
        {
            DataTable dt = (DataTable)this.gcParam.DataSource;

            if (dt == null)
            {
                MessageBox.Show("无核算结果", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (dt.Rows.Count > 0)
            {
                // SaveFileDialog saveFileDialog = new SaveFileDialog() { Title = "生成Word", Filter = "Word文件(*.doc)|*.docx" };
                DialogResult dialogResult = saveFileDialog.ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    try
                    {
                        SplashScreenManager.ShowForm(typeof(DevWaitForm));
                        List <CafcService.FuelCafcAndTcafc> cafcData = new List <CafcService.FuelCafcAndTcafc>();
                        if (Convert.ToInt32(this.comboBoxEdit1.Text) > 2015)
                        {
                            var data = Utils.serviceCafc.QueryForeCastNECafc(Utils.userId, Utils.password, "prj_" + Utils.userId);
                            if (data != null && data.Length > 0)
                            {
                                cafcData = data.ToList();
                            }
                        }
                        else
                        {
                            var data = Utils.serviceCafc.QueryForeCastTECafc(Utils.userId, Utils.password, "prj_" + Utils.userId);
                            if (data != null && data.Length > 0)
                            {
                                cafcData = data.ToList();
                            }
                        }
                        if (cafcData.Count > 0)
                        {
                            Dictionary <string, string> datas = new Dictionary <string, string>();
                            datas.Add("{qymc}", Utils.qymc);
                            datas.Add("{year}", comboBoxEdit1.Text);
                            datas.Add("{count}", cafcData[0].Sl_act.ToString());
                            datas.Add("{tcafc}", cafcData[0].Tcafc.ToString());
                            datas.Add("{cafc}", cafcData[0].Cafc.ToString());
                            decimal percent = (cafcData[0].Tcafc - cafcData[0].Cafc) / cafcData[0].Tcafc;
                            percent = percent * 10;
                            percent = Math.Round(percent, 1, MidpointRounding.ToEven);
                            datas.Add("{percent}", percent.ToString());
                            WordHelper wordBuilder = new WordHelper();
                            wordBuilder.CreateNewDocument(forecast);
                            foreach (var item in datas)
                            {
                                wordBuilder.InsertReplaceText(item.Key, item.Value);
                            }
                            wordBuilder.SaveDocument(saveFileDialog.FileName);
                            if (MessageBox.Show("生成成功,是否打开文件?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                            {
                                System.Diagnostics.Process.Start(saveFileDialog.FileName);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    finally
                    {
                        SplashScreenManager.CloseForm();
                    }
                }
            }
            else
            {
                MessageBox.Show("请导入预测车型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
示例#16
0
        private void FillScore()
        {
            RemoveNoScoreRows();

            // 建立對照
            foreach (JHCourseRecord cr in _courseDict.Values)
            {
                if (!_SubjCourseDict.ContainsKey(cr.Subject))
                {
                    _SubjCourseDict.Add(cr.Subject, cr);
                }
            }

            //_SubjCourseDict = _courseDict.Values.Distinct().ToDictionary(x => x.Subject);

            _builder.MoveToMergeField("成績");
            Cell indexCell = _builder.CurrentParagraph.ParentNode as Cell;

            try
            {
                //排序
                List <string> domains = new List <string>(_manager.Domains.Keys);
                domains.Sort(JHSchool.Evaluation.Subject.CompareDomainOrdinal);

                foreach (var domainName in _manager.Domains.Keys)
                {
                    DomainRow domain = _manager.Domains[domainName];


                    bool display = false;
                    if (_config.PrintDomains.ContainsKey(domain.DomainName))
                    {
                        display = CheckDisplayDomain(domain);
                        //   display = _config.PrintDomains[domain.DomainName];
                    }
                    else
                    {
                        display = domain.Display;
                    }

                    if (_config.DomainSubjectSetup == "Domain")
                    {
                        if (display)
                        {
                            Cell temp = indexCell;
                            indexCell = WordHelper.GetMoveDownCell(indexCell, 1);
                            WriteDomainRowOnly(temp, domain);
                            // WordHelper.MergeHorizontalCell(temp, 2);
                            if (indexCell == null)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (domain.Subjects.Count > 0)
                        {
                            int  count = WriteDomainRow(indexCell, domain);
                            Cell temp  = indexCell;
                            indexCell = WordHelper.GetMoveDownCell(indexCell, count);
                            WordHelper.MergeVerticalCell(temp, count);
                            if (indexCell == null)
                            {
                                break;
                            }
                        }
                    }
                }

                // 算科目加權平均
                if (SubjSumCredit > 0)
                {
                    // 定期
                    //SubjAvgScore = Math.Round(SubjSumScore / SubjSumCredit, 2, MidpointRounding.AwayFromZero);
                    SubjAvgScore = _calculator.ParseSubjectScore(SubjSumScore / SubjSumCredit);
                }

                if (SubjSumCreditAss > 0)
                {
                    // 平時
                    SubjAvgAssignmentScore = _calculator.ParseSubjectScore(SubjSumAssignmentScore / SubjSumCreditAss);
                }
                // 總分
                if (SubjSumFinalCredit > 0)
                {
                    SubjAvgFinalScore = _calculator.ParseSubjectScore(SubjSumFinalScore / SubjSumFinalCredit);
                }


                // 算領域加權平均
                if (DomainSumCredit > 0)
                {
                    //DomainAvgScore = Math.Round(DomainSumScore / DomainSumCredit, 2, MidpointRounding.AwayFromZero);
                    DomainAvgScore = _calculator.ParseDomainScore(DomainSumScore / DomainSumCredit);
                }
                if (DomainSumCreditAss > 0)
                {
                    DomainAvgAssignmentScore = _calculator.ParseDomainScore(DomainSumAssignmentScore / DomainSumCreditAss);
                }
                if (DomainSumFinalCredit > 0)
                {
                    DomainAvgFinalScore = _calculator.ParseDomainScore((DomainSumFinalScore) / DomainSumFinalCredit);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#17
0
        private void FillDomainRows()
        {
            Cell  cell        = _cell;
            Row   row         = _cell.ParentRow;
            Table table       = row.ParentTable;
            int   deleteIndex = table.IndexOf(row);
            int   rowIndex    = table.IndexOf(row);

            foreach (DomainRow domainRow in _manager.DomainRows)
            {
                // 透過對照表查詢領域是否需要展開
                bool display = DomainSubjectExpand.展開;
                if (_domains.ContainsKey(domainRow.Domain))
                {
                    display = _domains[domainRow.Domain];
                }

                // 不展開,列印領域
                if (display == DomainSubjectExpand.展開)
                {
                    if (domainRow.Scores.Count <= 0)
                    {
                        continue;
                    }

                    table.Rows.Add(row.Clone(true));
                    Row tempRow = table.LastRow;
                    WordHelper.MergeHorizontalCell(tempRow.Cells[0], 2);
                    WordHelper.Write(tempRow.Cells[0], (string.IsNullOrEmpty(domainRow.Domain) ? "彈性課程" : domainRow.Domain), _builder);
                    WriteDomain(tempRow.Cells[1], domainRow);
                }
                // 展開,列印科目
                else
                {
                    int subjectCount = 0;
                    foreach (string subject in domainRow.SubjectScores.Keys)
                    {
                        subjectCount++;

                        table.Rows.Add(row.Clone(true));
                        Row tempRow = table.LastRow;

                        WordHelper.Write(tempRow.Cells[1], subject, _builder);
                        WriteSubject(tempRow.Cells[1], domainRow.SubjectScores[subject]);
                    }
                    // 當只有領域成績沒有科目成績時
                    if (subjectCount > 0)
                    {
                        Row startRow = table.Rows[table.Rows.Count - subjectCount];
                        WordHelper.Write(startRow.Cells[0], (string.IsNullOrEmpty(domainRow.Domain) ? "彈性課程" : domainRow.Domain), _builder);
                        if (subjectCount > 1)
                        {
                            WordHelper.MergeVerticalCell(startRow.Cells[0], subjectCount);
                        }
                    }
                }

                //// 畢業成績  (畢業成績讀取法,因為目前高雄沒有畢業成績,新竹有,所以暫註)
                //if (_StudGradScore.Domains.ContainsKey(domainRow.Domain))
                //{
                //    Row tmpRow = table.LastRow;
                //    if (_StudGradScore.Domains[domainRow.Domain].Score.HasValue)
                //    {
                //        // 分數
                //        WordHelper.Write(tmpRow.Cells[20], _StudGradScore.Domains[domainRow.Domain].Score.Value.ToString(), _builder);
                //        // 等第
                //        WordHelper.Write(tmpRow.Cells[21], DegreeMapper.GetDegreeByScore(_StudGradScore.Domains[domainRow.Domain].Score.Value), _builder);
                //    }
                //}
            }

            table.Rows[deleteIndex].Remove();
        }
示例#18
0
        private int WriteDomainRow(Cell indexCell, DomainRow domain)
        {
            try
            {
                // 判斷領域名稱是否需要顯示
                bool DisplayDomain = CheckDisplayDomain(domain);

                if (DisplayDomain)
                {
                    Write(indexCell, string.IsNullOrEmpty(domain.DomainName) ? "彈性課程" : domain.DomainName);
                }

                Cell subjectCell = WordHelper.GetMoveRightCell(indexCell, 1);
                int  count       = 0;
                foreach (var subjectName in domain.Subjects.Keys)
                {
                    // 判斷是否需要顯示科目
                    bool DisplaySubject = true;

                    if (_SubjCourseDict.ContainsKey(subjectName))
                    {
                        if (_config.HasExam(_SubjCourseDict[subjectName]) == false)
                        {
                            DisplaySubject = false;
                        }
                    }

                    if (DisplaySubject == false)
                    {
                        continue;
                    }

                    SubjectRow row = domain.Subjects[subjectName];
                    if (row.Display)
                    {
                        Cell temp = subjectCell;
                        Write(temp, row.SubjectName);
                        temp = temp.NextSibling as Cell;
                        Write(temp, GetPCDisplay(row.PeriodCredit));

                        // 依照成績計算規則設定
                        // 定期評量
                        if (PrintScore)
                        {
                            temp = temp.NextSibling as Cell;
                            if (row.Score.HasValue)
                            {
                                Write(temp, "" + _calculator.ParseSubjectScore(row.Score.Value));
                            }
                            else
                            {
                                Write(temp, "");
                            }
                        }

                        // 平時評量
                        if (PrintAssScore)
                        {
                            temp = temp.NextSibling as Cell;
                            if (row.AssignmentScore.HasValue)
                            {
                                Write(temp, "" + _calculator.ParseSubjectScore(row.AssignmentScore.Value));
                            }
                            else
                            {
                                Write(temp, "");
                            }
                        }

                        // 定期學習評量總成績
                        if (PrintTotalScore)
                        {
                            temp = temp.NextSibling as Cell;
                            if (row.FinalScore.HasValue)
                            {
                                Write(temp, "" + _calculator.ParseSubjectScore(row.FinalScore.Value));
                            }
                            else
                            {
                                Write(temp, "");
                            }
                        }

                        // 文字評語
                        if (PrintText)
                        {
                            temp = temp.NextSibling as Cell;
                            Write(temp, "" + row.Text);
                        }

                        subjectCell = WordHelper.GetMoveDownCell(subjectCell, 1);
                        count++;

                        // 定期評量加權平均
                        if (row.Score.HasValue)
                        {
                            SubjSumScore  += (row.Score.Value * row.Credit);
                            SubjSumCredit += row.Credit;
                        }

                        // 平時評量加權平均
                        if (row.AssignmentScore.HasValue)
                        {
                            SubjSumAssignmentScore += (row.AssignmentScore.Value * row.Credit);
                            SubjSumCreditAss       += row.Credit;
                        }
                        // 學習總成績加權平均
                        if (row.FinalScore.HasValue)
                        {
                            SubjSumFinalScore  += (row.FinalScore.Value * row.Credit);
                            SubjSumFinalCredit += row.Credit;
                        }
                        if (subjectCell == null)
                        {
                            break;
                        }
                    }
                }
                return(count);
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#19
0
 // 當Null可以給預設值用
 private void ProcessItemNameIsNull(DocumentBuilder builder, string mergeFieldName, string str)
 {
     builder.MoveToMergeField(mergeFieldName);
     WordHelper.Write(builder.CurrentParagraph.ParentNode as Cell, builder.Font, str);
 }
示例#20
0
        /// <summary>
        /// 處理領域顯示
        /// </summary>
        /// <param name="indexCell"></param>
        /// <param name="domain"></param>
        private void WriteDomainRowOnly(Cell indexCell, DomainRow domain)
        {
            try
            {
                // 判斷領域名稱是否需要顯示
                bool DisplayDomain1 = CheckDisplayDomain(domain);

                if (DisplayDomain1)
                {
                    // 當領域為空白時需要另外處理
                    if (string.IsNullOrEmpty(domain.DomainName))
                    {
                        Cell subjectCell = WordHelper.GetMoveRightCell(indexCell, 1);
                        int  count       = 0;
                        foreach (var subjectName in domain.Subjects.Keys)
                        {
                            // 判斷是否需要顯示科目
                            bool DisplaySubject = true;

                            if (_SubjCourseDict.ContainsKey(subjectName))
                            {
                                if (_config.HasExam(_SubjCourseDict[subjectName]) == false)
                                {
                                    DisplaySubject = false;
                                }
                            }

                            if (DisplaySubject == false)
                            {
                                continue;
                            }

                            SubjectRow row = domain.Subjects[subjectName];
                            if (row.Display)
                            {
                                Cell temp1 = subjectCell;
                                Write(temp1, row.SubjectName);
                                temp1 = temp1.NextSibling as Cell;
                                Write(temp1, GetPCDisplay(row.PeriodCredit));

                                // 依照成績計算規則
                                // 定期評量
                                if (PrintScore)
                                {
                                    temp1 = temp1.NextSibling as Cell;
                                    if (row.Score.HasValue)
                                    {
                                        Write(temp1, "" + _calculator.ParseSubjectScore(row.Score.Value));
                                    }
                                    else
                                    {
                                        Write(temp1, "");
                                    }
                                }

                                // 平時評量
                                if (PrintAssScore)
                                {
                                    temp1 = temp1.NextSibling as Cell;
                                    if (row.AssignmentScore.HasValue)
                                    {
                                        Write(temp1, "" + _calculator.ParseSubjectScore(row.AssignmentScore.Value));
                                    }
                                    else
                                    {
                                        Write(temp1, "");
                                    }
                                }
                                // 定期學習評量總成績
                                if (PrintTotalScore)
                                {
                                    temp1 = temp1.NextSibling as Cell;
                                    if (row.FinalScore.HasValue)
                                    {
                                        Write(temp1, "" + _calculator.ParseSubjectScore(row.FinalScore.Value));
                                    }
                                    else
                                    {
                                        Write(temp1, "");
                                    }
                                }

                                // 文字評語
                                if (PrintText)
                                {
                                    temp1 = temp1.NextSibling as Cell;
                                    Write(temp1, "" + row.Text);
                                }

                                subjectCell = WordHelper.GetMoveDownCell(subjectCell, 1);
                                count++;

                                // 算領域加權平均
                                if (row.Score.HasValue)
                                {
                                    DomainSumScore  += row.Score.Value * row.Credit;
                                    DomainSumCredit += row.Credit;
                                }

                                // 算領域平時評量加權平均
                                if (row.AssignmentScore.HasValue)
                                {
                                    DomainSumAssignmentScore += row.AssignmentScore.Value * row.Credit;
                                    DomainSumCreditAss       += row.Credit;
                                }

                                // 算領域學習總分加權平均
                                if (row.FinalScore.HasValue)
                                {
                                    DomainSumFinalScore  += row.FinalScore.Value * row.Credit;
                                    DomainSumFinalCredit += row.Credit;
                                }
                                if (subjectCell == null)
                                {
                                    break;
                                }
                            }
                        }
                        WordHelper.MergeVerticalCell(indexCell, count);
                        Write(indexCell, "彈性課程");
                    }
                    else
                    {
                        WordHelper.MergeHorizontalCell(indexCell, 2);
                        Write(indexCell, domain.DomainName);
                        Cell temp = indexCell.NextSibling as Cell;
                        temp = temp.NextSibling as Cell;
                        Write(temp, GetPCDisplay(domain.PeriodCredit));

                        // 定期評量
                        if (PrintScore)
                        {
                            temp = temp.NextSibling as Cell;
                            Write(temp, (domain.Score.HasValue ? "" + _calculator.ParseDomainScore(domain.Score.Value) : ""));
                        }

                        // 平時評量
                        if (PrintAssScore)
                        {
                            temp = temp.NextSibling as Cell;
                            Write(temp, (domain.AssignmentScore.HasValue ? "" + _calculator.ParseDomainScore(domain.AssignmentScore.Value) : ""));
                        }

                        // 定期學習評量總成績
                        if (PrintTotalScore)
                        {
                            temp = temp.NextSibling as Cell;
                            Write(temp, (domain.FinalScore.HasValue ? "" + _calculator.ParseDomainScore(domain.FinalScore.Value) : ""));
                        }

                        // 文字評語
                        if (PrintText)
                        {
                            temp = temp.NextSibling as Cell;
                            Write(temp, domain.Text);
                        }

                        // 算領域加權平均
                        if (domain.Score.HasValue)
                        {
                            decimal crd;
                            if (decimal.TryParse(GetPCDisplay(domain.PeriodCredit), out crd))
                            {
                                DomainSumScore  += (domain.Score.Value * crd);
                                DomainSumCredit += crd;
                            }
                        }

                        // 算領域平時評量加權平均
                        if (domain.AssignmentScore.HasValue)
                        {
                            decimal crd;
                            if (decimal.TryParse(GetPCDisplay(domain.PeriodCredit), out crd))
                            {
                                DomainSumAssignmentScore += (domain.AssignmentScore.Value * crd);
                                DomainSumCreditAss       += crd;
                            }
                        }

                        // 算領域學習總成績加權平均
                        if (domain.FinalScore.HasValue)
                        {
                            decimal crd;
                            if (decimal.TryParse(GetPCDisplay(domain.PeriodCredit), out crd))
                            {
                                DomainSumFinalScore  += (domain.FinalScore.Value * crd);
                                DomainSumFinalCredit += crd;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#21
0
 private void InitTable()
 {
     this.clbTable.DataSource = WordHelper.GetTableList();
 }
示例#22
0
 private void Write(Cell cell, string text)
 {
     WordHelper.Write(cell, text, _builder);
 }
示例#23
0
        private void ProcessDiscipline(List <AutoSummaryRecord> autoSummaryList)
        {
            #region 定位,產生Row
            _builder.MoveToMergeField("獎懲");
            Cell  currentCell = _builder.CurrentParagraph.ParentNode as Cell;
            Row   currentRow  = currentCell.ParentRow;
            Table table       = currentRow.ParentTable;

            int rowCount    = 6;
            int insertIndex = table.Rows.IndexOf(currentRow) + 1;
            for (int i = 1; i < rowCount; i++)
            {
                table.Rows.Insert(insertIndex, currentRow.Clone(true));
            }
            #endregion

            string postfix = "次數";

            #region 寫入獎勵資料
            Dictionary <string, ValueItemRow> items = new Dictionary <string, ValueItemRow>();

            foreach (string name in new string[] { "嘉獎", "小功", "大功" })
            {
                items.Add(name + postfix, new ValueItemRow(name + postfix));
            }

            foreach (AutoSummaryRecord record in autoSummaryList)
            {
                SemesterData semester = new SemesterData("" + record.SchoolYear, "" + record.Semester);

                items["大功" + postfix].Add(semester, record.MeritA);
                items["小功" + postfix].Add(semester, record.MeritB);
                items["嘉獎" + postfix].Add(semester, record.MeritC);
            }

            Cell cell = currentCell;

            WordHelper.MergeVerticalCell(cell, 3);
            WordHelper.Write(cell, "獎勵", _builder);

            Cell itemCell = WordHelper.GetMoveRightCell(cell, 1);
            foreach (string type in items.Keys)
            {
                WriteValueItemRow(itemCell, items[type]);
                itemCell = WordHelper.GetMoveDownCell(itemCell, 1);
                if (itemCell == null)
                {
                    break;
                }
            }

            Cell tempCell = WordHelper.GetMoveDownCell(cell, 3);
            if (tempCell != null)
            {
                cell = tempCell;
            }
            currentCell = cell;
            #endregion

            #region 寫入懲戒資料
            items.Clear();

            foreach (string name in new string[] { "警告", "小過", "大過" })
            {
                items.Add(name + postfix, new ValueItemRow(name + postfix));
            }

            foreach (var record in autoSummaryList)
            {
                SemesterData semester = new SemesterData("" + record.SchoolYear, "" + record.Semester);

                items["大過" + postfix].Add(semester, record.DemeritA);
                items["小過" + postfix].Add(semester, record.DemeritB);
                items["警告" + postfix].Add(semester, record.DemeritC);
            }

            cell = currentCell;

            WordHelper.MergeVerticalCell(cell, 3);
            WordHelper.Write(cell, "懲戒", _builder);

            itemCell = WordHelper.GetMoveRightCell(cell, 1);
            foreach (string type in items.Keys)
            {
                WriteValueItemRow(itemCell, items[type]);
                itemCell = WordHelper.GetMoveDownCell(itemCell, 1);
                if (itemCell == null)
                {
                    break;
                }
            }

            tempCell = WordHelper.GetMoveDownCell(cell, 3);
            if (tempCell != null)
            {
                cell = tempCell;
            }
            #endregion
        }
示例#24
0
        private int WriteDomainRow(Cell indexCell, DomainRow domain)
        {
            WordHelper.Write(indexCell, _font, string.IsNullOrEmpty(domain.DomainName) ? "彈性課程" : domain.DomainName);
            int  col         = 0;
            Cell subjectCell = WordHelper.GetMoveRightCell(indexCell, 1);
            int  count       = 0;

            foreach (var subjectName in domain.Subjects.Keys)
            {
                SubjectRow row = domain.Subjects[subjectName];
                if (row.Display)
                {
                    Cell temp = subjectCell;
                    WordHelper.Write(temp, _font, row.SubjectName);
                    temp = temp.NextSibling as Cell;
                    WordHelper.Write(temp, _font, row.PeriodCredit);

                    foreach (string examID in row.Scores.Keys)
                    {
                        ScoreData data       = row.Scores[examID];
                        string    effortText = string.Empty;
                        if (data.Effort.HasValue)
                        {
                            effortText = _effortMapper.GetTextByInt(data.Effort.Value);
                        }

                        temp = WordHelper.GetMoveRightCell(subjectCell, _columnMapping[examID] - 1);
                        WordHelper.Write(temp, _font, (data.Score.HasValue ? "" + _calculator.ParseSubjectScore(data.Score.Value) : ""));
                        WordHelper.Write(temp.NextSibling as Cell, _font, effortText);
                    }

                    if (_AttendDict.ContainsKey(subjectName))
                    {
                        temp = WordHelper.GetMoveRightCell(subjectCell, _columnMapping["平時評量"] - 1);

                        // 平時
                        if (_AttendDict[subjectName].OrdinarilyScore.HasValue)
                        {
                            WordHelper.Write(temp, _font, _calculator.ParseSubjectScore(_AttendDict[subjectName].OrdinarilyScore.Value).ToString());
                        }
                        else
                        {
                            WordHelper.Write(temp, _font, "");
                        }

                        if (_AttendDict[subjectName].OrdinarilyEffort.HasValue)
                        {
                            WordHelper.Write(temp.NextSibling as Cell, _font, _effortMapper.GetTextByInt(_AttendDict[subjectName].OrdinarilyEffort.Value));
                        }
                        else
                        {
                            WordHelper.Write(temp.NextSibling as Cell, _font, "");
                        }


                        //temp = WordHelper.GetMoveRightCell(indexCell, _columnMapping["課程總成績"]);

                        //// 課程總成績
                        //if (_AttendDict[subjectName].Score.HasValue)
                        //    WordHelper.Write(temp, _font, _calculator.ParseSubjectScore(_AttendDict[subjectName].Score.Value).ToString());
                        //else
                        //    WordHelper.Write(temp, _font, "");

                        //if (_AttendDict[subjectName].Effort.HasValue)
                        //    WordHelper.Write(temp.NextSibling as Cell, _font, _effortMapper.GetTextByInt(_AttendDict[subjectName].Effort.Value));
                        //else
                        //    WordHelper.Write(temp.NextSibling as Cell, _font, "");
                    }

                    subjectCell = WordHelper.GetMoveDownCell(subjectCell, 1);

                    if (subjectCell == null)
                    {
                        break;
                    }
                    count++;
                }
            }
            return(count);
        }
示例#25
0
        public StudentMoralProcessor(DocumentBuilder builder, SemesterMap map)
        {
            _builder = builder;

            _map   = map;
            _types = new Dictionary <string, List <string> >();

            _run = WordHelper.CreateRun(_builder);

            #region 取得假別設定
            ConfigData cd = K12.Data.School.Configuration["學籍表"];
            if (cd.Contains("假別設定"))
            {
                XmlElement config = Framework.XmlHelper.LoadXml(cd["假別設定"]);

                foreach (XmlElement type in config.SelectNodes("Type"))
                {
                    string typeName = type.GetAttribute("Text");
                    if (!_types.ContainsKey(typeName))
                    {
                        _types.Add(typeName, new List <string>());
                    }

                    foreach (XmlElement absence in type.SelectNodes("Absence"))
                    {
                        string absenceName = absence.GetAttribute("Text");
                        if (!_types[typeName].Contains(absenceName))
                        {
                            _types[typeName].Add(absenceName);
                        }
                    }
                }
            }
            #endregion

            #region 取得社團成績
            _assnScoreCache = new Dictionary <string, List <AssnScore> >();

            FISCA.UDT.AccessHelper ah = new FISCA.UDT.AccessHelper();
//            string condition = string.Format("SchoolYear='{0}' and Semester='{1}'", options.SchoolYear, options.Semester);
//            List<AssnCode> list = ah.Select<AssnCode>(condition);

            if (AssociationUDTCache == null)
            {
                AssociationUDTCache = ah.Select <AssnCode>();
            }

            List <AssnCode> list = AssociationUDTCache;
            foreach (AssnCode record in list)
            {
                //if (!_assnScoreCache.ContainsKey(record.StudentID))
                //{
                XmlElement scores      = K12.Data.XmlHelper.LoadXml(record.Scores);
                XmlElement itemElement = (XmlElement)scores.SelectSingleNode("Item");
                if (itemElement != null)
                {
                    AssnScore assnScore = new AssnScore()
                    {
                        Score      = itemElement.GetAttribute("Score"),
                        Effort     = itemElement.GetAttribute("Effort"),
                        Text       = itemElement.GetAttribute("Text"),
                        SchoolYear = record.SchoolYear,
                        Semester   = record.Semester
                    };
                    if (_assnScoreCache.ContainsKey(record.StudentID))
                    {
                        _assnScoreCache[record.StudentID].Add(assnScore);
                    }
                    else
                    {
                        List <AssnScore> lis = new List <AssnScore>();
                        lis.Add(assnScore);
                        _assnScoreCache.Add(record.StudentID, lis);
                    }
                }
                //}
            }

            //<Content>
            //<Item AssociationName="籃球社" Score="" Effort="" Text=""></Item>
            //</Content>
            #endregion
        }
示例#26
0
        private void WriteDomainRowOnly(Cell indexCell, DomainRow domain)
        {
            WordHelper.Write(indexCell, _font, domain.DomainName);
            Cell temp = indexCell.NextSibling as Cell;

            temp = temp.NextSibling as Cell;
            WordHelper.Write(temp, _font, domain.PeriodCredit);

            foreach (var examID in domain.ExamIDs)
            {
                decimal?score      = domain.GetScore(examID);
                string  effortText = string.Empty;
                if (score.HasValue)
                {
                    effortText = _effortMapper.GetTextByDecimal(score.Value);
                }

                temp = WordHelper.GetMoveRightCell(indexCell, _columnMapping[examID]);
                //                WordHelper.Write(temp, _font, (score.HasValue ? "" + _calculator.ParseDomainScore(score.Value) : ""));
                if (score.HasValue)
                {
                    WordHelper.Write(temp, _font, _calculator.ParseDomainScore(score.Value).ToString());
                }
                else
                {
                    WordHelper.Write(temp, _font, "");
                }

                WordHelper.Write(temp.NextSibling as Cell, _font, effortText);
            }


            // 平時
            if (_DomainScoreDict.ContainsKey(domain.DomainName))
            {
                temp = WordHelper.GetMoveRightCell(indexCell, _columnMapping["平時評量"]);
                string effortText1 = string.Empty;
                // 當有值
                if (_DomainScoreDict[domain.DomainName].HasValue)
                {
                    effortText1 = _effortMapper.GetTextByDecimal(_DomainScoreDict[domain.DomainName].Value);
                    WordHelper.Write(temp, _font, _calculator.ParseDomainScore(_DomainScoreDict[domain.DomainName].Value).ToString());
                }
                else
                {
                    WordHelper.Write(temp, _font, ""); // 沒有領域成績填空白
                }
                WordHelper.Write(temp.NextSibling as Cell, _font, effortText1);
            }
            //temp = temp.NextSibling as Cell;
            //temp = temp.NextSibling as Cell;

            //// 總
            //if (_DomainScoreDictTT.ContainsKey(domain.DomainName))
            //{
            //    temp = WordHelper.GetMoveRightCell(indexCell, _columnMapping["課程總成績"]);
            //    string effortText2 = string.Empty;
            //    effortText2 = _effortMapper.GetTextByDecimal(_DomainScoreDictTT[domain.DomainName]);

            //    WordHelper.Write(temp, _font, _calculator.ParseDomainScore(_DomainScoreDictTT[domain.DomainName]).ToString());
            //    WordHelper.Write(temp.NextSibling as Cell, _font, effortText2);
            //}
        }
示例#27
0
        private void ToolStripMenuItem_GenerateReport_Click(object sender, EventArgs e)
        {
            WordHelper     wh      = new WordHelper();
            SaveFileDialog sfd     = new SaveFileDialog();
            string         blkGrad = "";

            sfd.Filter = "Word File|*.doc|(*.*)|*.*";
            sfd.Title  = "保存文件";
            //sfd.ShowDialog();
            StringBuilder strBlocks = new StringBuilder();

            //******************************************************************//
            double        dbVal;
            List <double> wgtGeo    = new List <double>();
            List <double> wgtEng    = new List <double>();
            List <double> wgtEco    = new List <double>();
            DrawGraph     dgGeo     = null;
            Bitmap        bmGeo     = null;
            string        bmGeoPath = null;
            DrawGraph     dgEng     = null;
            Bitmap        bmEng     = null;
            string        bmEngPath = null;
            DrawGraph     dgEco     = null;
            Bitmap        bmEco     = null;
            string        bmEcoPath = null;

            //对地质参数用画图类的构造函数进行实例化
            if (PublicValues.ArrGeoParas.Length != 0)
            {
                foreach (string str in PublicValues.ArrGeoParas)
                {
                    PublicValues.DicGeoP_W.TryGetValue(str, out dbVal);
                    wgtGeo.Add(dbVal);
                }
                dgGeo     = new DrawGraph(PublicValues.ArrGeoParas, wgtGeo.ToArray(), "参数", "权重值", "黑体", 180);
                bmGeo     = dgGeo.DrawBarGraph();
                bmGeoPath = System.Windows.Forms.Application.StartupPath + "\\geoWgtBar.jpeg";
                bmGeo.Save(bmGeoPath, MyImage.ImageFormat.Jpeg);
            }


            //对工程参数用画图类的构造函数进行实例化
            if (PublicValues.ArrEngParas.Length != 0)
            {
                foreach (string str in PublicValues.ArrEngParas)
                {
                    PublicValues.DicEngP_W.TryGetValue(str, out dbVal);
                    wgtEng.Add(dbVal);
                }
                dgEng     = new DrawGraph(PublicValues.ArrEngParas, wgtEng.ToArray(), "参数", "权重值", "黑体", 180);
                bmEng     = dgEng.DrawBarGraph();
                bmEngPath = System.Windows.Forms.Application.StartupPath + "\\engWgtBar.jpeg";
                bmEng.Save(bmEngPath, MyImage.ImageFormat.Jpeg);
            }

            if (!strName.Contains("dgvBsn_TDM"))
            {
                // 对经济参数用画图类的构造函数进行实例化
                if (PublicValues.ArrEcoParas.Length != 0)
                {
                    foreach (string str in PublicValues.ArrEcoParas)
                    {
                        PublicValues.DicEcoP_W.TryGetValue(str, out dbVal);
                        wgtEco.Add(dbVal);
                    }
                    dgEco     = new DrawGraph(PublicValues.ArrEcoParas, wgtEco.ToArray(), "参数", "权重值", "黑体", 180);
                    bmEco     = dgEco.DrawBarGraph();
                    bmEcoPath = System.Windows.Forms.Application.StartupPath + "\\ecoWgtBar.jpeg";
                    bmEco.Save(bmEcoPath, MyImage.ImageFormat.Jpeg);
                }
            }


            bool isOpen = false;
            bool flag   = true;

            //******************************************************************//

            foreach (string str in arr_TgtName)
            {
                if (str != arr_TgtName.Last())
                {
                    strBlocks.Append(str + "、");
                }
                else
                {
                    strBlocks.Append(str + ";");
                }
            }
            if (strName.Contains("dgvBlk_TDM"))
            {
                blkGrad = "有利区";
            }
            if (strName.Contains("dgvBsn_TDM"))
            {
                blkGrad = "远景区";
            }
            if (strName.Contains("dgvTgt_TDM"))
            {
                blkGrad = "核心区";
            }
            string strFileName = null;

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                strFileName = sfd.FileName;
                wh.CreateWord(strFileName);
                wh.InsertText("页岩气选区评价结果分析", 18, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphCenter, 0);
                wh.NewLine();
                wh.InsertText("一、" + blkGrad + "参与评价区块", 16, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 0);
                wh.NewLine();
                wh.InsertText(strBlocks.ToString(), 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                wh.NewLine();
                wh.InsertText("二、TOPSIS方法评价参数、判断矩阵及权重", 16, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 0);
                wh.NewLine();
                wh.InsertText("2.1、地质因素", 14, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 20);
                wh.NewLine();
                wh.InsertText("2.1.1、评价参数", 14, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 25);
                wh.NewLine();
                if (PublicValues.ArrGeoParas.Length != 0)
                {
                    wh.InsertText(PublicValues.GeoParas, 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                }
                else
                {
                    wh.InsertText("没有地质参数参与评价。", 10, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                }
                //wh.InsertText(PublicValues.GeoParas, 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                wh.NewLine();
                wh.InsertText("2.1.2、判断矩阵", 14, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 25);
                wh.NewLine();
                flag = wh.DGV2Word(PublicValues.dgv_Geo);
                if (flag == false)
                {
                    return;
                }
                //wh.DGV2Word(PublicValues.dgv_Geo);
                //wh.NewLine();
                wh.InsertText("2.1.3、地质参数权重", 14, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 25);
                wh.NewLine();
                if (PublicValues.ArrGeoParas.Length != 0)
                {
                    wh.InsertPicture(bmGeoPath);
                }
                else
                {
                    wh.InsertText("没有地质参数参与评价。", 10, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                }
                //wh.InsertText(PublicValues.GeoWgt, 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                wh.NewLine();
                wh.InsertText("2.2、工程因素", 14, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 20);
                wh.NewLine();
                wh.InsertText("2.2.1、评价参数", 14, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 25);
                wh.NewLine();
                if (PublicValues.ArrEngParas.Length != 0)
                {
                    wh.InsertText(PublicValues.EngParas, 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                }
                else
                {
                    wh.InsertText("没有工程参数参与评价。", 10, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                }
                //wh.InsertText(PublicValues.EngParas, 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                wh.NewLine();
                wh.InsertText("2.2.2、判断矩阵", 14, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 25);
                wh.NewLine();
                wh.DGV2Word(PublicValues.dgv_Eng);
                //wh.NewLine();
                wh.InsertText("2.2.3、工程参数权重", 14, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 25);
                wh.NewLine();
                if (PublicValues.ArrEngParas.Length != 0)
                {
                    wh.InsertPicture(bmEngPath);
                }
                else
                {
                    wh.InsertText("没有工程参数参与评价。", 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                }
                //wh.InsertText(PublicValues.EngWgt, 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                wh.NewLine();
                if (!strName.Contains("dgvBsn_TDM"))
                {
                    wh.InsertText("2.3、经济因素", 14, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 20);
                    wh.NewLine();
                    wh.InsertText("2.3.1、评价参数", 14, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 25);
                    wh.NewLine();
                    if (PublicValues.ArrEcoParas.Length != 0)
                    {
                        wh.InsertText(PublicValues.EcoParas, 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                    }
                    else
                    {
                        wh.InsertText("没有经济参数参与评价。", 10, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                    }
                    //wh.InsertText(PublicValues.EcoParas, 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                    wh.NewLine();
                    wh.InsertText("2.3.2、判断矩阵", 14, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 25);
                    wh.NewLine();
                    wh.DGV2Word(PublicValues.dgv_Eco);
                    //wh.NewLine();
                    wh.InsertText("2.3.3、经济参数权重", 14, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 25);
                    wh.NewLine();
                    if (PublicValues.ArrEcoParas.Length != 0)
                    {
                        wh.InsertPicture(bmEcoPath);
                    }
                    else
                    {
                        wh.InsertText("没有经济参数参与评价。", 10, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                    }
                    //wh.InsertText(PublicValues.EcoWgt, 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                    wh.NewLine();
                }
                wh.InsertText("三、评价结果", 16, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 0);
                wh.NewLine();
                wh.InsertText("3.1、有利区", 14, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 20);
                wh.NewLine();
                if (strClass_1.Equals(null))
                {
                    MessageBox.Show("未对参数进行自然分类,所以分类评价结果为Null。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    wh.InsertText("Null", 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                    wh.NewLine();
                    wh.InsertText("3.2、一般区", 14, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 20);
                    wh.NewLine();
                    wh.InsertText("Null", 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                    wh.NewLine();
                    wh.InsertText("3.3、较差区", 14, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 20);
                    wh.NewLine();
                    wh.InsertText("Null", 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                }
                else
                {
                    wh.InsertText(strClass_1.ToString(), 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                    wh.NewLine();
                    wh.InsertText("3.2、一般区", 14, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 20);
                    wh.NewLine();
                    wh.InsertText(strClass_2.ToString(), 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                    wh.NewLine();
                    wh.InsertText("3.3、较差区", 14, 1, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 20);
                    wh.NewLine();
                    wh.InsertText(strClass_3.ToString(), 12, 0, "SimHei", MyWord.WdParagraphAlignment.wdAlignParagraphLeft, 30);
                }
                isOpen = wh.SaveWord(strFileName);
                if (isOpen == false)
                {
                    return;
                }
            }
            DialogResult dr = MessageBox.Show("报告已完成,是否打开该报告?。", "信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

            if (dr == DialogResult.Yes)
            {
                wh.OpenWordDoc(strFileName);
            }
            else
            {
                wh.QuitWordApp(strFileName);
            }
        }
示例#28
0
 public void GoWord()
 {
     WordHelper.InWord(Results.Select(x => Tuple.Create(x.Header, x.Description)), "Documents/Result.doc");
 }
        public void Should_ReturnFalse_When_WordLessThanMinLetters()
        {
            var result = WordHelper.CheckInput(new string[] { "a", "b" });

            Assert.AreEqual(result, false);
        }
示例#30
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                //模板文件
                string    tempFile = HttpContext.Current.Request.PhysicalApplicationPath + "Web\\upload\\yanyiting\\ApplyFormModel.docx";
                int       recode   = int.Parse(context.Request["recode"]);
                DataTable dt       = SqlHelper.ExecuteDataTable("select * from auditorium where id = @id",
                                                                new SqlParameter("@id", recode));
                if (dt.Rows.Count == 0)
                {
                    JavaScriptSerializer        jss = new JavaScriptSerializer();
                    Dictionary <string, object> dic = new Dictionary <string, object>();
                    dic.Add("result", "<h1 style='text-align:center;'>未找到结果,请尝试重新输入回执码!</h1>");
                    string jsonS = jss.Serialize(dic);
                    context.Response.Write(jsonS);
                    return;
                }

                //即将返回Json数据
                string url      = "upload/yanyiting/" + dt.Rows[0]["id"] + "_" + dt.Rows[0]["activity"] + ".docx";
                string filename = dt.Rows[0]["activity"].ToString();

                //提示
                string atag = "<br><a href='javascript:opendetail(" + dt.Rows[0]["id"] + ")'>查看申请表</a>";
                //string tips = "<p>您好!您申请的\" "+ dt.Rows[0]["activity"] + " \"已经处理</p>";
                string tips = "";
                status = Convert.ToInt32(dt.Rows[0]["status"]);
                if (status == 1)
                {
                    redata = tips + "<h1 style='text-align:center;color:green;'>申请成功</h1><p>" + ((DateTime)dt.Rows[0]["handle_time"]).ToString("F") + "</p>";
                    string saveFile = HttpContext.Current.Request.PhysicalApplicationPath + "Web\\upload\\yanyiting\\" + (dt.Rows[0]["id"].ToString()).Trim() + "_" + (dt.Rows[0]["activity"].ToString()).Trim() + "_1.docx";
                    //重新生成已通过文件
                    if (!File.Exists(saveFile))
                    {
                        WordHelper.ExportApplyForm(tempFile, saveFile, dt);
                    }
                    filename = dt.Rows[0]["activity"].ToString() + "(已更新)";
                    url      = "upload/yanyiting/" + dt.Rows[0]["id"] + "_" + dt.Rows[0]["activity"] + "_1.docx";
                }
                else if (status == 2)
                {
                    redata = tips + "<h1 style='text-align:center;color:red;'> 申请失败</h1><p>" + ((DateTime)dt.Rows[0]["handle_time"]).ToString("F") + "</p><p>失败原因:" + dt.Rows[0]["reason"] + "</p>";
                }
                else if (status == 3)
                {
                    redata = "<h1 style='text-align:center;color:red;'> 已取消</h1><p>" + ((DateTime)dt.Rows[0]["update_time"]).ToString("F") + "</p>";
                }
                else
                {
                    redata = "<h1 style='text-align:center;color:blue;'>申请中</h1>";
                }

                JavaScriptSerializer        json       = new JavaScriptSerializer();
                Dictionary <string, object> dictionaty = new Dictionary <string, object>();
                dictionaty.Add("result", redata);
                dictionaty.Add("status", status);
                dictionaty.Add("fileName", filename);
                dictionaty.Add("url", url);
                string jsonStr = json.Serialize(dictionaty);

                context.Response.Write(jsonStr);
            }
            catch (Exception e)
            {
                JavaScriptSerializer        json       = new JavaScriptSerializer();
                Dictionary <string, object> dictionaty = new Dictionary <string, object>();
                dictionaty.Add("result", "<h1 style='text-align:center;'>发生未知错误!</h1>");
                dictionaty.Add("status", 3);
                string jsonStr = json.Serialize(dictionaty);
                context.Response.Write(jsonStr);
            }
        }