Example #1
1
        public string GetReport()
        {
            try
            {
                _wordApp = new Word.Application();
                _doc = _wordApp.Documents.Add(_templateWordPath);

                _doc.Bookmarks["АрендаВЧас"].Range.Text = CostInHour.ToString("C0", new System.Globalization.CultureInfo("be-BY"));
                _doc.Bookmarks["Часов"].Range.Text = CountHours.ToString();
                _doc.Bookmarks["Арендатор"].Range.Text = Renter;
                _doc.Bookmarks["АрендаторПаспорт"].Range.Text = RenterPassport;
                _doc.Bookmarks["АрендаторТелефон"].Range.Text = RenterPhone;
                _doc.Bookmarks["АрендаторФИО"].Range.Text = RenterFIO;
                _doc.Bookmarks["Арендодатель"].Range.Text = LandLord;
                _doc.Bookmarks["АрендодательАдрес"].Range.Text = LandLordAddress;
                _doc.Bookmarks["АрендодательБанковскиеРеквизиты"].Range.Text = LandLordBank;
                _doc.Bookmarks["АрендодательЛицо"].Range.Text = LandLordFIO;
                _doc.Bookmarks["АрендодательНаименование"].Range.Text = LandLord;
                _doc.Bookmarks["АрендодательТелефон"].Range.Text = LandLordPhone;
                _doc.Bookmarks["Город"].Range.Text = City;
                _doc.Bookmarks["ГосНомер"].Range.Text = TransportRegNumber;
                _doc.Bookmarks["Дата"].Range.Text = Date.ToShortDateString();
                _doc.Bookmarks["ДатаНачалаДоговора"].Range.Text = ContractStartDate.ToShortDateString();
                _doc.Bookmarks["ДатаНеПозднее"].Range.Text = DateBeforeEnd.ToShortDateString();
                _doc.Bookmarks["ДатаОкончанияДоговора"].Range.Text = ContractEndDate.ToShortDateString();
                _doc.Bookmarks["НазваниеТС"].Range.Text = TransportName;
                _doc.Bookmarks["НазваниеТСКоммЭкс"].Range.Text = TransportName;
                _doc.Bookmarks["НазваниеТССубаренда"].Range.Text = TransportName;
                _doc.Bookmarks["Номер"].Range.Text = ContractNumber.ToString();
                _doc.Bookmarks["НомерКузова"].Range.Text = TransportEngineNumber;
                _doc.Bookmarks["НомерДвигателя"].Range.Text = TransportBodyNumber;
                _doc.Bookmarks["Пеня"].Range.Text = Fine.ToString();
                _doc.Bookmarks["СколькоЧеловек"].Range.Text = CrewCount.ToString();
                _doc.Bookmarks["СтоимостьАренды"].Range.Text = RentCost.ToString("C0", new System.Globalization.CultureInfo("be-BY"));
                _doc.Bookmarks["ТранспортноеСредство"].Range.Text = TransportName;
                _doc.Bookmarks["ЦелевоеНазначение"].Range.Text = TransportSpecialPurpose;

                _doc.SaveAs2(FileName: _documnetSavePath, FileFormat: Word.WdSaveFormat.wdFormatPDF);

                return _documnetSavePath;
            }
            catch (Exception)
            {
            }
            finally
            {
                _doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                _wordApp.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
            }
            return null;
        }
Example #2
0
        public void ExtractMathTypes()
        {
            statusLabel.Text   = "Converting MathType Equations To KaTeX...";
            inputSolutionPath  = inputPathTextBox.Text + @"\";
            outputSolutionPath = outputPathTextBox.Text + @"\";
            fpath      = inputSolutionPath.ToString();
            MathMLPath = fpath;
            int count;
            int fileCounter = 0;

            try
            {
                //string MMLpath = outputSolutionPath + "/KaTeXFiles";

                //if (!Directory.Exists(MMLpath))
                //{
                //    Directory.CreateDirectory(MMLpath);
                //}

                string logPath = outputSolutionPath + "/Done Files/Logs";

                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }

                DirectoryInfo di = new DirectoryInfo(MathMLPath);

                int tFiles = di.GetFiles("*.docx", SearchOption.AllDirectories).Length;
                //int tFiles = Directory.GetFiles(MathMLPath,".docx").Length;
                string[] allfiles = Directory.GetFiles(MathMLPath, "*.docx", SearchOption.AllDirectories);

                MSWord.Application app = new MSWord.Application();
                statusBar.Maximum = tFiles;
                statusBar.Minimum = 0;

                using (StreamWriter er = new StreamWriter(logPath + "/" + "MathType-Error-Log.csv"))
                {
                    using (StreamWriter lr = new StreamWriter(logPath + "/" + "MathType-Conversion-Log.csv"))
                    {
                        DateTime now = DateTime.Now;
                        lr.WriteLine("Word to KaTeX - V-0.2.0.0");
                        //lr.WriteLine("Book code, Folder name,Number of files converted to KaTeX,Start time,End Time");
                        lr.WriteLine("Process start time:," + now.ToString("F"));
                        //lr.WriteLine("------------------------------------------------------------------");
                        foreach (string file in allfiles)
                        {
                            Console.WriteLine(Path.GetFileNameWithoutExtension(file));
                            List <string> mathMLList = new List <string>();
                            List <string> KatexList  = new List <string>();
                            fileCounter    += 1;
                            statusBar.Value = fileCounter;
                            // mathMLList.Clear();
                            try
                            {
                                MSWord.Document doc = app.Documents.Open(file, ReadOnly: false);
                                statusBox.AppendText(Path.GetFileName(file).ToString().Replace(".docx", "").ToString() + "-" + "(" + fileCounter.ToString() + " of " + tFiles.ToString() + ")" + "-");
                                count = 0;
                                List <MSWord.Range> ranges = new List <Microsoft.Office.Interop.Word.Range>();
                                // ranges.Clear();

                                foreach (MSWord.Section sec in doc.Sections)
                                {
                                    foreach (MSWord.Paragraph para in sec.Range.Paragraphs)
                                    {
                                        foreach (InlineShape ishape in para.Range.InlineShapes)
                                        {
                                            Boolean isMathType = false;
                                            Boolean isDelete   = false;
                                            try
                                            {
                                                if (ishape.OLEFormat.ProgID.StartsWith("Equation."))
                                                {
                                                    try
                                                    {
                                                        MathTypeEquation mobj = new MathTypeEquation(ishape.OLEFormat);

                                                        //textBox4.AppendText(mobj.LaTeX + Environment.NewLine);
                                                        //  Console.WriteLine("Converted Latex:"+ mobj.LaTeX);
                                                        mathMLList.Add(mobj.LaTeX);
                                                        while (isMathType == false)
                                                        {
                                                            // Console.WriteLine("Math Object disposed!");
                                                            mobj.Dispose();
                                                            isMathType = true;
                                                        }

                                                        //Console.WriteLine("MathType Object Closeded");
                                                        while (isMathType == true && isDelete == false)
                                                        {
                                                            ranges.Add(ishape.Range);
                                                            ishape.Delete();
                                                            //Console.WriteLine("ishape deleted.");
                                                            isDelete = true;
                                                        }

                                                        // Console.WriteLine("isMathType: " + isMathType.ToString() + Environment.NewLine + "isDeleted: " + isDelete.ToString() + Environment.NewLine);
                                                        count++;
                                                    }
                                                    catch (NullReferenceException exce)
                                                    {
                                                        //Console.WriteLine(exce.Message);
                                                        continue;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        //Console.WriteLine(ex.ToString());
                                                        // MessageBox.Show(ex.ToString() + Environment.NewLine + count.ToString());
                                                    }
                                                }
                                            }
                                            catch (NullReferenceException exce)
                                            {
                                                //Console.WriteLine(exce.Message);
                                                continue;
                                            }
                                            catch (Exception ex)
                                            {
                                                //Console.WriteLine(ex.Message);
                                                continue;
                                            }
                                        }
                                    }

                                    foreach (Process process in Process.GetProcessesByName("MathType"))
                                    {
                                        process.Kill();
                                    }
                                }


                                //----------

                                // using (StreamWriter wr = new StreamWriter(MMLpath + "/" + Path.GetFileName(file).ToString().Replace(".docx", "") + ".txt"))
                                //{
                                foreach (string item in mathMLList)
                                {
                                    //.Replace("&", "")
                                    string citem = item.ToString().Replace(Environment.NewLine, "").Replace(@"\[", @"\(").Replace(@"\]", @"\)").Replace(@"\begin{align}", @"\begin{aligned}").Replace(@"\end{align}", @"\end{aligned}").Replace("{}", "").Replace("&", "").Replace("=", "&=").Replace("{&=}", "{=}");
                                    Regex  regex = new Regex(@"text{(\s)*");
                                    foreach (Match ItemMatch in regex.Matches(citem))
                                    {
                                        string filler = String.Concat(Enumerable.Repeat(@"\,", (ItemMatch.Value.Length - 5)));
                                        textBox1.AppendText(citem + " <> " + ItemMatch.Value + "-" + "text{" + filler + Environment.NewLine);
                                        if (citem.Contains(ItemMatch.Value))
                                        {
                                            textBox1.AppendText("True" + Environment.NewLine);
                                        }
                                        var regex1 = new Regex(Regex.Escape(ItemMatch.Value));
                                        citem = regex1.Replace(citem, "text{" + filler, 1);
                                    }

                                    if (citem.Contains(@"\begin{matrix}"))
                                    {
                                        citem = citem.Replace(@"\begin{matrix}", @"\begin{array}{cccccccc}").Replace(@"\end{matrix}", @"\end{array}").Replace("   ", "").Replace("  ", "&&").Replace(@"&\\", @"\\\\").Replace("frac", "cfrac").Replace(@"&\\\\", @"\\\\").Replace(@"\\\\\end", @"\\\end").Replace("cdots", "cdots&&").Replace("vdots", "vdots&&").Replace("ddots", "ddots&&");
                                        er.WriteLine("WARNING! - " + Path.GetFileName(file).ToString() + ": Check if the matrix at index " + (mathMLList.IndexOf(item) + 1).ToString() + " in the solution file contains any verticle line or horizontal line in it. Please use the matrix guidelines for KaTeX to resolve the issue");
                                    }

                                    if (citem.Contains(@"\begin{array}"))
                                    {
                                        citem = citem.Replace(@"{*{35}{l}}", "{cccccc}").Replace("  ", "&").Replace(@"&\\\", @"\\\").Replace(@"{cccccc}&", @"{cccccc}");
                                    }

                                    if (citem.ToString().Contains("aligned"))
                                    {
                                        citem = citem.Replace(@"\approx", @"&\approx ");
                                        //do nothing
                                        //citem = citem.Replace(").Replace(@"\ne", @"&\ne ");
                                    }
                                    else
                                    {
                                        citem = citem.Replace("&=", "=").Replace(@"&\ne", @"\ne");
                                    }

                                    //textBox3.AppendText(citem.Substring(0,2) + "-" + citem.Substring(citem.Length-2,2) + Environment.NewLine);
                                    //.Replace(" ", "")
                                    citem = citem.Replace(@"{\rm E}", @"\Epsilon").Replace(@"\varepsilon", @"\epsilon").Replace(@"\ne", @"\ne ").Replace(@"\ne g", @"\neg ").Replace(@"\le", @"\le ").Replace("le ft", "left").Replace(@"\partial", @"\partial ").Replace("cdot", "cdot ").Replace("cdot s", "cdots").Replace(@"\Delta", @"\Delta ").Replace(@"\delta", @"\delta ").Replace(@"%", @"\%").Replace(@"\ \ \ \ \ \ \ \ \ \ \ \ \ \ \", " ");

                                    string tempStr = citem.Replace(@"\(", "").Replace(@"\)", "");

                                    Regex reg = new Regex(@"\(([^)]+)\)*");
                                    foreach (Match ItemMatch in reg.Matches(tempStr))
                                    {
                                        string temp = ItemMatch.Value.Replace("&=", "=");
                                        citem = citem.Replace(ItemMatch.Value, temp);
                                    }

                                    Regex reg1 = new Regex(@"\{([^)]+)\}}*");
                                    foreach (Match ItemMatch in reg.Matches(tempStr))
                                    {
                                        string temp = ItemMatch.Value.Replace("&=", "=");
                                        citem = citem.Replace(ItemMatch.Value, temp);
                                    }

                                    if (citem.Substring(0, 1) == "$")
                                    {
                                        citem = citem.Trim('$');
                                        citem = @"\(" + citem + @"\)";
                                    }
                                    //if (citem.Substring(citem.Length - 1, 1) == "$")
                                    //{
                                    //    citem = citem.Replace(citem.Substring(citem.Length - 1, 1), @"\)");
                                    //}
                                    citem = citem.Replace(@"\cdot", @"\cdot ").Replace(@"\cdot s", @"\cdots").Replace(@"&&\\", @"\\").Replace(@"\ne g", @"\neg ");

                                    if (isChemistry.Checked)
                                    {
                                        citem = citem.Replace(@"\Xi", @"\overrightharpoon{\,_\leftharpoondown}");
                                    }
                                    citem = citem.Trim();
                                    KatexList.Add(citem);
                                    // wr.WriteLine(citem);
                                }
                                // wr.Close();
                                // }
                                // mathMLList.Clear();

                                //---------------
                                int mcount = 0;
                                foreach (MSWord.Range r in ranges)
                                {
                                    // replace image with image
                                    // r.InlineShapes.AddPicture(@"D:\New folder\img1.jpg", ref missing, ref missing, ref missing);
                                    // replace image with text
                                    //string rlen = r.Text.ToString();
                                    //statusBox.AppendText(rlen + Environment.NewLine);

                                    r.Text = KatexList[mcount].ToString();

                                    mcount++;
                                }


                                lr.WriteLine(Path.GetFileName(file).ToString().Replace(".docx", "") + "," + count.ToString() + " MathType(s) Converted.");
                                statusBox.AppendText(count.ToString() + " MathType(s) Converted." + Environment.NewLine);


                                string tempPath = outputSolutionPath + "Done Files\\";

                                string tempFilePath = tempPath + Path.GetFileName(Path.GetDirectoryName(file));
                                if (!Directory.Exists(tempFilePath))
                                {
                                    Directory.CreateDirectory(tempFilePath);
                                }

                                doc.SaveAs2(tempFilePath + @"\" + Path.GetFileName(file));
                                doc.Close();
                            }
                            catch (Exception ex)
                            {
                                //MessageBox.Show(ex.ToString());
                                statusBox.AppendText(ex.Message.ToString() + Environment.NewLine);
                            }
                        }
                        //lr.WriteLine("------------------------------------------------------------------");
                        lr.WriteLine("Total files processed:," + tFiles.ToString());
                        //lr.WriteLine("------------------------------------------------------------------");
                        DateTime now1 = DateTime.Now;
                        lr.WriteLine("Process end time:," + now1.ToString("F"));
                        //lr.WriteLine("------------------------------------------------------------------");
                        lr.WriteLine("");
                        lr.WriteLine("For any query regarding KaTeX, please write to [email protected]");
                        lr.Close();
                    }
                    er.WriteLine("");
                    //er.WriteLine("------------------------------------------------------------------");
                    er.WriteLine("For any query regarding KaTeX, please write to [email protected]");
                    er.Close();
                }

                app.Quit();
            }
            catch { }
            //MessageBox.Show("MathType Conversion Done" + Environment.NewLine + @"click on ""Go Back"" button.", "Latex Converter");
            Console.ReadLine();
        }
Example #3
0
 private void RaportBtn_Click(object sender, RoutedEventArgs e)
 {
     if (DGridConsumable.SelectedItem == null)
     {
         return;
     }
     else
     {
         SaveFileDialog openDlg = new SaveFileDialog();
         openDlg.FileName         = "Отчет №";
         openDlg.Filter           = "Word (.doc)|*.doc |Word (.docx)|*.docx |All files (*.*)|*.*";
         openDlg.FilterIndex      = 2;
         openDlg.RestoreDirectory = true;
         if (openDlg.ShowDialog() == true)
         {
             Word.Application word = new Microsoft.Office.Interop.Word.Application();
             Word.Document    doc  = word.Documents.Open(Environment.CurrentDirectory + @"\Tovarny_otchyot_-_materialy.doc");
             var SelectedInfo      = DGridConsumable.SelectedItems.Cast <ReplenishmentOfMaterials>().FirstOrDefault() as ReplenishmentOfMaterials;
             var info           = AccountingForConsumablesEntities.GetContext().MaterialsInDelivery.Where(w => w.FK_Replenishment == SelectedInfo.id).FirstOrDefault();
             var XHuman1        = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 1).Select(s => s.FirstName + " " + s.MiddleName.Substring(0, 1) + " " + s.LastName.Substring(0, 1)).FirstOrDefault();
             var XHuman2        = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 5).Select(s => s.FirstName + " " + s.MiddleName.Substring(0, 1) + " " + s.LastName.Substring(0, 1)).FirstOrDefault();
             var XHuman3        = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 9).Select(s => s.FirstName + " " + s.MiddleName.Substring(0, 1) + " " + s.LastName.Substring(0, 1)).FirstOrDefault();
             var NameOfMaterial = info.MaterialCard.Materials.MaterialName;
             var Date           = DateTime.Now.ToShortDateString();
             var date2          = DateTime.Now.AddDays(7).ToShortDateString();
             var date3          = info.ReplenishmentOfMaterials.DateOfAcceptanceToTheWarehouse.ToShortDateString();
             var Number         = info.ReplenishmentOfMaterials.ContractNumber;
             var Worker1        = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 2).FirstOrDefault();
             var Worker2        = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 34).FirstOrDefault();
             var GetDate        = DateTime.Today.ToShortDateString();
             try
             {
                 ReplaceWordStub("{getdate1}", Date, doc);
                 ReplaceWordStub("{GetDate2}", Date, doc);
                 ReplaceWordStub("{FirstDate}", date2, doc);
                 ReplaceWordStub("{DateOfDelivery}", date3, doc);
                 ReplaceWordStub("{Number}", Number, doc);
                 ReplaceWordStub("{FirstName1}", Worker1.FirstName, doc);
                 ReplaceWordStub("{FirstName2}", Worker1.FirstName, doc);
                 ReplaceWordStub("{FirstName3}", Worker2.FirstName, doc);
                 ReplaceWordStub("{LastName1}", Worker1.LastName, doc);
                 ReplaceWordStub("{LastName2}", Worker1.LastName, doc);
                 ReplaceWordStub("{LastName3}", Worker2.LastName, doc);
                 ReplaceWordStub("{MiddleName1}", Worker1.MiddleName, doc);
                 ReplaceWordStub("{MiddleName2}", Worker1.MiddleName, doc);
                 ReplaceWordStub("{MiddleName3}", Worker2.MiddleName, doc);
                 ReplaceWordStub("{Position1}", Worker2.Position.PositionName, doc);
                 ReplaceWordStub("{Position2}", Worker1.Position.PositionName, doc);
                 ReplaceWordStub("{Position}", Worker1.Position.PositionName, doc);
                 ReplaceWordStub("{N}", info.id.ToString(), doc);
                 ReplaceWordStub("{N1}", info.id + 1000.ToString(), doc);
                 ReplaceWordStub("{NameOfMaterial}", NameOfMaterial, doc);
             }
             catch (Exception ex)
             {
                 MessageBox.Show("" + ex);
             }
             doc.SaveAs2(openDlg.FileName);
             doc.Close();
         }
     }
 }
Example #4
0
        public string GetReport()
        {
            try
            {
                _wordApp = new Word.Application();
                _doc = _wordApp.Documents.Add(_templateWordPath);

                _doc.Bookmarks["Адрес"].Range.Text = Address;
                _doc.Bookmarks["Дата"].Range.Text = Date.ToShortDateString();
                _doc.Bookmarks["Директор"].Range.Text = Director;
                _doc.Bookmarks["НаименованиеПредприятия"].Range.Text = Organization;
                _doc.Bookmarks["ОтФИО"].Range.Text = string.Format("{0} {1}. {2}.", LastName, Name.Substring(0, 1), MiddleName.Substring(0, 1));
                _doc.Bookmarks["ПаспортВыдан"].Range.Text = string.Format("{0} {1} г.", PassportIssuedBy, PassportIssuedDate.ToShortDateString());
                _doc.Bookmarks["ПаспортНомер"].Range.Text = PassportNumber;
                _doc.Bookmarks["ПаспортСерия"].Range.Text = PassportSeries;
                _doc.Bookmarks["Телефон"].Range.Text = Phone;
                _doc.Bookmarks["Услуга"].Range.Text = Service;
                _doc.Bookmarks["ФИО"].Range.Text = string.Format("{0} {1} {2}", LastName, Name, MiddleName);

                _doc.SaveAs2(FileName: _documnetSavePath, FileFormat: Word.WdSaveFormat.wdFormatPDF);

                return _documnetSavePath;
            }
            catch (Exception)
            {
            }
            finally
            {
                _doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                _wordApp.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
            }
            return null;
        }
Example #5
0
        public string GetReport()
        {
            try
            {
                _wordApp = new Word.Application();
                _doc = _wordApp.Documents.Add(_templateWordPath);

                _doc.Bookmarks["Город"].Range.Text = City;
                _doc.Bookmarks["Дата"].Range.Text = Date.ToShortDateString();
                _doc.Bookmarks["Заказчик"].Range.Text = Customer;
                _doc.Bookmarks["ЗаказчикПодпись"].Range.Text = CustomerInitials;
                _doc.Bookmarks["Исполнитель"].Range.Text = Executor;
                _doc.Bookmarks["ИсполнительПодпись"].Range.Text = ExecutorInitials;
                _doc.Bookmarks["НаименованиеПредприятия"].Range.Text = Organization;
                _doc.Bookmarks["СрокиПорядки"].Range.Text = TimeAndOrders;
                _doc.Bookmarks["СрокНачало"].Range.Text = StartDate.ToShortDateString();
                _doc.Bookmarks["СрокОкончание"].Range.Text = EndDate.ToShortDateString();
                _doc.Bookmarks["Стоимость"].Range.Text = Cost.ToString("C0", new System.Globalization.CultureInfo("be-BY"));
                _doc.Bookmarks["Услуги"].Range.Text = Service;

                _doc.SaveAs2(FileName: _documnetSavePath, FileFormat: Word.WdSaveFormat.wdFormatPDF);

                return _documnetSavePath;
            }
            catch (Exception)
            {
            }
            finally
            {
                _doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                _wordApp.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
            }
            return null;
        }
Example #6
0
        private void GenerateManagerReport()
        {
            var FileName = "MANAGERREPORT-"
                           + dbs.ap_period.Where(m => m.EndDate <= today).Max(m => m.APPeriodID)
                           + ".docx";

            var WeekProviders = GetAPPeriodProviders();

            //Create a new document
            Microsoft.Office.Interop.Word.Application winword  = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    document = winword.Documents.Add();

            //Add header into the document
            foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
            {
                Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                headerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlack;
                headerRange.Font.Size = 20;
                headerRange.Text      = "Weekly Billing Report";
            }

            document.Content.SetRange(0, 0);
            document.Content.Text = "AP Period: " + lastWeek.ToShortDateString() +
                                    " - " + today.ToShortDateString() + Environment.NewLine;

            Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add();

            para1.Range.InsertParagraphAfter();
            Table firstTable = document.Tables.Add(para1.Range, WeekProviders.Count + 1, 3);

            firstTable.Borders.Enable = 1;
            var c  = firstTable.Rows.Count;
            var c2 = firstTable.Columns.Count;

            foreach (Row row in firstTable.Rows)
            {
                foreach (Cell cell in row.Cells)
                {
                    //Header row
                    if (cell.RowIndex == 1)
                    {
                        if (cell.ColumnIndex == 1)
                        {
                            cell.Range.Text = "Provider Name";
                        }
                        else if (cell.ColumnIndex == 2)
                        {
                            cell.Range.Text = "# of Consultations";
                        }
                        else
                        {
                            cell.Range.Text = "Billed Amount";
                        }
                    }
                    else
                    {
                        var thisProvider = WeekProviders[cell.RowIndex - 2];
                        if (cell.ColumnIndex == 1)
                        {
                            cell.Range.Text = thisProvider.FirstName + " " + thisProvider.LastName;
                        }
                        else if (cell.ColumnIndex == 2)
                        {
                            cell.Range.Text = GetAPPeriodConsulationsPerProvider(thisProvider).ToString();
                        }
                        else
                        {
                            cell.Range.Text = "$" + GetAPPeriodBillingPerProvider(thisProvider).ToString();
                        }
                    }
                }
            }


            Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add();
            para2.Range.InsertParagraphAfter();
            Table lastTable = document.Tables.Add(para2.Range, 2, 4);

            lastTable.Borders.Enable = 1;
            foreach (Row row in lastTable.Rows)
            {
                foreach (Cell cell in row.Cells)
                {
                    if (cell.RowIndex == 1)
                    {
                        if (cell.ColumnIndex == 1)
                        {
                            cell.Range.Text = "TOTALS";
                        }
                        else if (cell.ColumnIndex == 2)
                        {
                            cell.Range.Text = "Providers";
                        }
                        else if (cell.ColumnIndex == 3)
                        {
                            cell.Range.Text = "Consultations";
                        }
                        else
                        {
                            cell.Range.Text = "Billing";
                        }
                    }
                    else
                    {
                        if (cell.ColumnIndex == 1)
                        {
                            cell.Range.Text = "";
                        }
                        else if (cell.ColumnIndex == 2)
                        {
                            cell.Range.Text = WeekProviders.Count.ToString();
                        }
                        else if (cell.ColumnIndex == 3)
                        {
                            cell.Range.Text = GetAPPeriodConsulations().ToString();
                        }
                        else
                        {
                            cell.Range.Text = "$" + GetAPPeriodBilling().ToString();
                        }
                    }
                }
            }

            //Add the footers into the document
            foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
            {
                //Get the footer range and add the footer details.
                Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                footerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlack;
                footerRange.Font.Size                 = 10;
                footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                footerRange.Text = FileName;
            }

            //Save the document
            object filename = FileName;

            document.SaveAs2(ref filename);
            document.Close();
            document = null;
            winword.Quit();
            winword = null;
        }
Example #7
0
        private Document creatAAO()
        {
            List <string> prodinfo = DbHelperSQL.getlistcol("select 图号,图纸名称,下级装配号,图纸版次,AOI编号,预铆编号 from 产品列表 where 名称='" + rncaao["名称"] + "'");

            // rncaao.Add("类型", "AAO返修");
            try
            {
                rncaao.Add("图号", prodinfo[0]);
                rncaao.Add("图纸名称", prodinfo[1]);
                rncaao.Add("下级装配号", prodinfo[2]);
                rncaao.Add("图纸版次", prodinfo[3]);
                if (comboBox1.Text == "自动钻铆")
                {
                    rncaao.Add("编号", prodinfo[4].Substring(0, 8) + "--AAO");
                }
                else
                {
                    rncaao.Add("编号", "C1-" + prodinfo[5] + "--AAO");

                    rncaao["保存地址"] = Program.InfoPath + rncaao["名称"] + "_" + rncaao["图号"] + "\\" + rncaao["架次"] + @"\" + rncaao["图号"] + "_CHANGEAAO.doc";
                }
            }
            catch
            {
            }


            wordApp         = new Microsoft.Office.Interop.Word.Application();
            wordApp.Visible = true;
            myAO            = new Document();
            if (File.Exists(rncaao["保存地址"]) && (!checkBox1.Checked))
            {
                myAO = wordApp.Documents.Open(rncaao["保存地址"]);
            }
            else
            {
                //myAO = wordApp.Documents.Add();


                myAO = wordApp.Documents.Open(@"\\192.168.3.32\Autorivet\Prepare\INFO\SAMPLE\AAO.doc");


                //下一级装配件号
                myAO.Tables[1].Cell(2, 2).Range.Text = rncaao["下级装配号"];
                string baseno = rncaao["编号"];

                int aaocount = DbHelperSQL.getlist("select 文件编号 from Paperwork where 文件编号 like '" + baseno + "%'").Count();



                myAO.Tables[1].Cell(2, 6).Range.Text = baseno + (aaocount + 1).ToString();
                //   }



                //发文目的


                //标题
                if (comboBox1.Text != "更改")
                {
                    string neibujushou = rncaao["内部拒收号"];
                    myAO.Tables[1].Cell(2, 4).Range.Text = "配合文件RNC:" + neibujushou + "进行排故\rACCORDING TO RNC: " + neibujushou + " REPAIR";

                    myAO.Tables[1].Cell(3, 1).Range.Text = "发放AAO目的 The Intent Of The Document Is: 根据编号为" + neibujushou + "的RNC对产品进行返修。 ACCORDING TO RNC: " + neibujushou;
                    myAO.Tables[1].Cell(4, 1).Range.Text = "TO REWORK FOR THE PRODUCT.";
                }


                //工程图纸号
                myAO.Tables[1].Cell(5, 2).Range.Text = rncaao["图号"].Replace("-001", "");
                //版次
                string banci = rncaao["图纸版次"][1].ToString();
                myAO.Tables[1].Cell(5, 4).Range.Text = banci;
                //第一条

                myAO.Tables[1].Cell(7, 1).Range.Text = "1";
                myAO.Tables[1].Cell(7, 2).Range.Text = rncaao["图号"] + "P2";
                myAO.Tables[1].Cell(7, 4).Range.Text = "1";
                myAO.Tables[1].Cell(7, 6).Range.Text = rncaao["名称"] + rncaao["图纸名称"];
                // myAO.Tables[1].Cell(7, 10).Range.Text = rncaao["架次"];
                // myAO.Tables[1].Cell(7, 1).Range.Text = dataGridView1.Rows[0].

                //开始统计紧固件
                int fstcount = fasteners.Count();
                if (fstcount != 0)
                {
                    int nut5 = 0;
                    int nut6 = 0;
                    for (int i = 0; i < fstcount; i++)
                    {
                        string fstname = fasteners.Keys.ElementAt(i);
                        myAO.Tables[1].Cell(8 + i, 1).Range.Text = (i + 2).ToString();
                        myAO.Tables[1].Cell(8 + i, 2).Range.Text = fasteners.Keys.ElementAt(i);

                        myAO.Tables[1].Cell(8 + i, 4).Range.Text = fasteners[fstname];
                        if (fstname.Contains("B020600"))
                        {
                            myAO.Tables[1].Cell(8 + i, 6).Range.Text = "高锁 HI-LITE";
                            int hiqty = System.Convert.ToInt16(fasteners[fstname]);

                            if (fstname.Contains("AG5"))
                            {
                                nut5 = nut5 + hiqty;
                            }
                            else
                            {
                                nut6 = nut6 + hiqty;
                            }
                        }
                        else
                        {
                            myAO.Tables[1].Cell(8 + i, 6).Range.Text = "铆钉 RIVET";
                        }
                    }
                    fstcount = 8 + fstcount;
                    if (nut5 != 0)
                    {
                        myAO.Tables[1].Cell(fstcount, 1).Range.Text = (fstcount - 6).ToString();
                        myAO.Tables[1].Cell(fstcount, 6).Range.Text = "高锁帽 NUT";
                        myAO.Tables[1].Cell(fstcount, 2).Range.Text = "B0203013-08";
                        myAO.Tables[1].Cell(fstcount, 4).Range.Text = nut5.ToString();

                        if (nut6 != 0)
                        {
                            fstcount = fstcount + 1;
                            myAO.Tables[1].Cell(fstcount, 1).Range.Text = (fstcount - 6).ToString();
                            myAO.Tables[1].Cell(fstcount, 6).Range.Text = "高锁帽 NUT";
                            myAO.Tables[1].Cell(fstcount, 2).Range.Text = "B0203013-3";
                            myAO.Tables[1].Cell(fstcount, 4).Range.Text = nut6.ToString();
                        }
                    }
                    else
                    {
                        if (nut6 != 0)
                        {
                            //fstcount = fstcount + 1;
                            myAO.Tables[1].Cell(fstcount, 1).Range.Text = (fstcount - 6).ToString();
                            myAO.Tables[1].Cell(fstcount, 6).Range.Text = "高锁帽 NUT";
                            myAO.Tables[1].Cell(fstcount, 2).Range.Text = "B0203013-3";
                            myAO.Tables[1].Cell(fstcount, 4).Range.Text = nut6.ToString();
                        }
                    }
                    //添加密封胶
                    if ((nut5 + nut6) == 0)
                    {
                    }
                    else
                    {
                        fstcount = fstcount + 1;
                    }



                    myAO.Tables[1].Cell(fstcount, 1).Range.Text = (fstcount - 6).ToString();
                    myAO.Tables[1].Cell(fstcount, 6).Range.Text = "密封剂 SEALANT";
                    myAO.Tables[1].Cell(fstcount, 2).Range.Text = "MIL-PRF-81733 Type IV P/S C-24";
                    myAO.Tables[1].Cell(fstcount, 4).Range.Text = "100g";
                }

                //架次
                myAO.Tables[1].Cell(15, 4).Range.Text = rncaao["架次"];
                myAO.Tables[1].Cell(15, 6).Range.Text = rncaao["图号"];
                myAO.SaveAs2(rncaao["保存地址"]);
            }
            FormMethod.scanfiledoc(rncaao["保存地址"], myAO, false);
            MessageBox.Show("生成完毕,请补全其他信息");
            return(myAO);
        }
        public static bool SaveCompare(bool ForceSave, bool SaveDoc)
        {
            try
            {
                //  int seq = 1;
                string strFileAttached = _fileName;
                if (strFileAttached != null)
                {
                    //Save the Contract
                    Globals.ThisAddIn.RemoveSaveHandler(); // remove the save handler to stop the save calling the save etc.

                    // if this is the first save - then save everything
                    if (_firstsave) ForceSave = true;

                    Globals.ThisAddIn.ProcessingStart("Save Contract");
                    DataReturn dr;
                    _doc = Globals.ThisAddIn.Application.ActiveDocument;

                    /*
                    Globals.ThisAddIn.ProcessingUpdate("Get the Clause Values");
                    foreach (Word.ContentControl cc in _doc.Range().ContentControls)
                    {
                        if (cc.Tag != null)
                        {
                            string tag = cc.Tag;
                            string docclausename = cc.Title;
                            Globals.ThisAddIn.ProcessingUpdate("Save " + docclausename);

                            string text = cc.Range.Text;
                            string[] taga = cc.Tag.Split('|');
                            if (taga[0] == "Concept")
                            {
                                dr = AxiomIRISRibbon.Utility.HandleData(_d.SaveDocumentClause("", _versionid, taga[1], taga[2], docclausename, seq++, text, false));
                            }
                            else if (taga[0] == "element")
                            {

                                dr = AxiomIRISRibbon.Utility.HandleData(_d.SaveDocumentClauseElement("",docclausename ,taga[2],"",_templateid,text,text ));

                            }
                        }
                    }

                    */

                    /*   List<string> clauseArray = new List<string>();
                       DataReturn ribbonClauseDr = _d.getRibbonClause(_templateid);
                       //check condition
                       DataTable ribbonClauseDt = ribbonClauseDr.dt;
                       foreach (Word.ContentControl cc in _doc.Range().ContentControls)
                       {
                           //
                           if (cc.Tag != null)
                           {
                               //
                               string tag = cc.Tag;
                               string docclausename = cc.Title;
                           }
                           string text = cc.Range.Text;
                           string[] taga = cc.Tag.Split('|');
                           if (taga[0] == "Concept")
                           {
                               //
                               if (!clauseArray.Contains(taga[2]))
                               {
                                   //
                                   clauseArray.Add(taga[2]);
                               }
                               //dr = _d.SaveRibbonClause(ribbonClauseDt, taga[1], taga[2], _templateid);
                           }
                       }
                       if (clauseArray.Count > 0)
                       {
                           dr = _d.SaveRibbonClause(ribbonClauseDt, clauseArray, _templateid);
                       }

                       */

                    dr = AxiomIRISRibbon.Utility.HandleData(_d.SaveVersion(_versionid, _matterid, _templateid, _versionName, _versionNumber));
                    if (!dr.success) return false;
                    _versionid = dr.id;

                    if (SaveDoc)
                    {
                        //Save the file as an attachment
                        //save this to a scratch file
                        Globals.ThisAddIn.ProcessingUpdate("Save Scratch");
                        _doc.SaveAs2(FileName: strFileAttached, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent);

                        //Save a copy because document open in split view cannot be locked for upload
                        //into IRIS
                        Globals.ThisAddIn.ProcessingUpdate("Save Copy");
                        string filenamecopy = AxiomIRISRibbon.Utility.SaveTempFile(_versionid + "X");
                        System.IO.File.Copy(strFileAttached, filenamecopy); // Create a copy

                        // Now save the copied file - change this to always save as the version name
                        Globals.ThisAddIn.ProcessingUpdate("Save To SalesForce");
                        string vfilename = _versionName.Replace(" ", "_") + ".docx";
                        dr = AxiomIRISRibbon.Utility.HandleData(_d.UpdateFile(_attachmentid, vfilename, filenamecopy));
                    }

                    Globals.ThisAddIn.AddSaveHandler(); // add it back in
                    Globals.ThisAddIn.ProcessingStop("End");

                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error saving contract");
                return false;
            }
        }
Example #9
0
        public static bool CreateWordsDocumentToOne(object docPath, string savaAs, string docName,DataRowView[] candidats,string presedinte,string membru1, string membru2)
        {
            int candiLength = candidats.Length;
               Console.WriteLine("LENGTH" + candiLength);

               object missing = Missing.Value;
             //      Word.Document[] adocs = new Word.Document[candidats.Length];

               string output = savaAs + docName + "-" + "candidats.docx";

               Application createEmptyDocApp = null;
               Word.Document createEmptyDoc = null;

               Word._Application wordAppForOutput = null;
               Word._Document wordDocument = null;

               Word.Document aDoc = null;
               Word.Application wordApp = null;

               try
               {
               if (File.Exists(output))
                   File.Delete(output);

               if (!File.Exists(output))
               {
                   createEmptyDocApp = new Application();
                   createEmptyDoc = createEmptyDocApp.Documents.Add();

                   createEmptyDocApp.ActiveDocument.SaveAs(output, ref missing, ref missing,
                                                                          ref missing, ref missing, ref missing, ref missing,
                                                                          ref missing, ref missing, ref missing, ref missing);
                   createEmptyDoc.Close();
                   if (createEmptyDocApp != null)
                   {
                       createEmptyDocApp.Quit();
                       Marshal.FinalReleaseComObject(createEmptyDocApp);
                   }

                   createEmptyDoc = null;
                   createEmptyDocApp = null;

               }
               else
               {
                   return false;
               }

               object pageBreak = Word.WdBreakType.wdPageBreak;
               wordAppForOutput = new Word.Application();

               wordAppForOutput.Visible = false;

               wordDocument = wordAppForOutput.Documents.Open(
                                             output
                                             , false, false, ref missing,
                                                        ref missing, ref missing, ref missing, ref missing,
                                                        ref missing, ref missing, ref missing, true,
                                                        ref missing, ref missing, ref missing, ref missing);

               wordDocument.Activate();

               for (int i = 0; i < candiLength; ++i)
               {

                   aDoc = new Word.Document();
                   wordApp = new Word.Application();
                   DataRow candidat = candidats[i].Row;
                   List<int> processesbeforegen = getRunningProcesses();
                   // string savePath =(string) savaAs + docName + " " + candidat["Nume"] + "_" + candidat["Prenume"] ;
                   string savePath = savaAs + "tempDoc";

                   if (File.Exists((string)docPath))
                   {
                       Console.WriteLine("Fajlnal vagyok");

                       object readOnly = false; //default
                       object isVisible = false;

                       wordApp.Visible = false;

                       aDoc = wordApp.Documents.Open(ref docPath, ref missing, ref readOnly,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing, ref missing);

                       aDoc.Activate();

                       Console.WriteLine("megnyitva");

                       //Find and replace:
                       FindAndReplace(wordApp, "{NrMatricol}", candidat["NrMatricol"]);
                       FindAndReplace(wordApp, "{Nume}", candidat["Nume"]);
                       FindAndReplace(wordApp, "{Prenume}", candidat["Prenume"]);
                       FindAndReplace(wordApp, "{Tata}", candidat["Tata"]);
                       FindAndReplace(wordApp, "{Mama}", candidat["Mama"]);
                       FindAndReplace(wordApp, "{CNP>", candidat["CNP"]);
                       FindAndReplace(wordApp, "{DataNasterii}", candidat["DataNasterii"]);
                       FindAndReplace(wordApp, "{LoculNasterii}", candidat["LoculNasterii"]);
                       FindAndReplace(wordApp, "{Strada}", candidat["Strada"]);
                       FindAndReplace(wordApp, "{Nr}", candidat["Nr"]);
                       FindAndReplace(wordApp, "{Bloc}", candidat["Bloc"]);
                       FindAndReplace(wordApp, "{Scara}", candidat["Scara"]);
                       FindAndReplace(wordApp, "{Ap}", candidat["Ap"]);
                       FindAndReplace(wordApp, "{Localitate}", candidat["Localitate"]);
                       FindAndReplace(wordApp, "{Judet}", candidat["Judet"]);
                       FindAndReplace(wordApp, "{Cp}", candidat["Cp"]);
                       FindAndReplace(wordApp, "{Telefon}", candidat["Telefon"]);
                       FindAndReplace(wordApp, "{Studii}", candidat["Studii"]);
                       FindAndReplace(wordApp, "{Profesia}", candidat["Profesia"]);
                       FindAndReplace(wordApp, "{LocMunca}", candidat["LocMunca"]);
                       FindAndReplace(wordApp, "{Presedinte}", presedinte);
                       FindAndReplace(wordApp, "{Membru1}", membru1);
                       FindAndReplace(wordApp, "{Membru2}", membru2);

                       Console.WriteLine("cserelgetes");

                       object saveFullPath = savePath;

                       aDoc.SaveAs2(ref saveFullPath, ref missing, ref missing, ref missing,
                       ref missing, ref missing, ref missing,
                       ref missing, ref missing, ref missing,
                       ref missing, ref missing, ref missing,
                       ref missing, ref missing, ref missing);

                       //Close Document:

                       aDoc.Close(ref missing, ref missing, ref missing);
                       wordApp.Quit(false);

                       Marshal.FinalReleaseComObject(wordApp);
                       string PathToMerge = savePath + ".docx";
                       if (File.Exists(PathToMerge))
                       {
                           wordAppForOutput.Selection.InsertFile(PathToMerge, ref missing, true, ref missing, ref missing);
                           wordAppForOutput.Selection.InsertBreak(ref pageBreak);
                           File.Delete(PathToMerge);
                       }
                       else
                       {
                           Console.WriteLine("dosent exist the file");
                       }

                       aDoc = null;
                       wordApp = null;
                       List<int> processesaftergen = getRunningProcesses();
                       Console.WriteLine("COUNT > " + processesbeforegen.Count + "  " + processesaftergen.Count);
                       killProcesses(processesbeforegen, processesaftergen);
                   }
                   else
                   {
                       System.Windows.MessageBox.Show("file dose not exist.");
                       return false;
                   }
               }

               // Clean up!
               wordDocument.SaveAs(output, ref missing, ref missing,
                                            ref missing, ref missing, ref missing,
                                            ref missing, ref missing, ref missing, ref missing, ref missing);
               wordDocument.Close(ref missing, ref missing, ref missing);
               wordAppForOutput.Quit(ref missing, ref missing, ref missing);
               Marshal.FinalReleaseComObject(wordAppForOutput);
               wordDocument = null;
               wordAppForOutput = null;
               }
               catch (Exception ex)
               {
               System.Windows.MessageBox.Show("Error occured at Report!");
               return false;
               }
               finally
               {
               if (createEmptyDoc != null) createEmptyDoc.Close(ref missing, ref missing, ref missing);
               if (createEmptyDocApp != null)
               {
                   createEmptyDocApp.Quit(ref missing, ref missing, ref missing);
                   Marshal.FinalReleaseComObject(createEmptyDocApp);
               }

               if (wordDocument != null) wordDocument.Close(ref missing, ref missing, ref missing);
               if (wordAppForOutput != null)
               {
                   wordAppForOutput.Quit(ref missing, ref missing, ref missing);
                   Marshal.FinalReleaseComObject(wordAppForOutput);
               }

               if (aDoc != null) aDoc.Close(ref missing, ref missing, ref missing);
               if (wordApp != null)
               {
                   wordApp.Quit(ref missing, ref missing, ref missing);
                   Marshal.FinalReleaseComObject(wordApp);
               }

               }

               return true;
        }
        // Save Amend Document
        public static bool SaveAmend(bool ForceSave, bool SaveDoc, bool IsTemplate)
        {
            try
            {
                //System.Windows.Forms.MessageBox.Show("SaveAmend ");
                string strFileToSave, strVfilename, strAttachmentId;

                Globals.ThisAddIn.RemoveSaveHandler(); // remove the save handler to stop the save calling the save etc.

                //Globals.ThisAddIn.ProcessingStart("Save Contract");
                DataReturn dr;

                if (!IsTemplate)
                {
                    strFileToSave = _strAmendmentDocumentPath;
                    if (_versionName != null)
                    {
                        strVfilename = _versionName.Replace(" ", "_") + ".docx";
                    }
                    else { strVfilename = _strAmendmentDocumentName; }

                    strAttachmentId = _strNewAttachmentId;

                    // Globals.ThisAddIn.AddDocId(objtempDocAmendment, "Contract", "");
                }
                else
                {
                    strFileToSave = _strAmendmentTemplatePath;
                    if (_versionName != null)
                    {
                        strVfilename = _versionName.Replace(" ", "_") + "_Amendment.docx";
                    }
                    else
                    {

                        strVfilename = _strAmendmentTemplateName;
                    }
                    strAttachmentId = _strAmendmentAttachmentId;

                    //   Globals.ThisAddIn.AddDocId(objtempAmendmentTemplate, "Contract", "");
                }

                if (SaveDoc)
                {
                    _doc = Globals.ThisAddIn.Application.Documents[strVfilename];
                    //save this to a scratch file
                    //Globals.ThisAddIn.ProcessingUpdate("Save Scratch");
                    _doc.SaveAs2(FileName: strFileToSave, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent);
                    //System.Windows.Forms.MessageBox.Show(" _doc.SaveAs2 ");

                    //Save a copy!
                    Globals.ThisAddIn.ProcessingUpdate("Save Copy");
                    string filenamecopy = AxiomIRISRibbon.Utility.SaveTempFile(_versionid + "Y");
                    Word.Document dcopy = Globals.ThisAddIn.Application.Documents.Add(strFileToSave, Visible: false);
                    dcopy.SaveAs2(FileName: filenamecopy, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent);
                    //System.Windows.Forms.MessageBox.Show(" dcopy.SaveAs2 ");
                    var docclose = (Word._Document)dcopy;
                    docclose.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(docclose);

                    Globals.ThisAddIn.ProcessingUpdate("Save To SalesForce");

                    dr = AxiomIRISRibbon.Utility.HandleData(_d.UpdateFile(strAttachmentId, strVfilename, filenamecopy));
                }
                Globals.ThisAddIn.AddSaveHandler(); // add it back in
                Globals.ThisAddIn.ProcessingStop("End");
                //System.Windows.Forms.MessageBox.Show("After End ");
                return true;
            }
            catch (Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show("After End ");
                return true;
            }
        }
        public bool SaveContract(bool ForceSave, bool SaveDoc)
        {
            string strFileAttached = _fileName;
            //Save the Contract
            Globals.ThisAddIn.RemoveSaveHandler(); // remove the save handler to stop the save calling the save etc.

            Globals.ThisAddIn.ProcessingStart("Save Contract");
            DataReturn dr;
              _doc = Globals.ThisAddIn.Application.ActiveDocument;

            dr = AxiomIRISRibbon.Utility.HandleData(_d.SaveVersion(_versionid, _matterid, _templateid, _versionName, _versionNumber));
            if (!dr.success) return false;
            _versionid = dr.id;

            if (SaveDoc)
            {

                //Save the file as an attachment
                //save this to a scratch file
                Globals.ThisAddIn.ProcessingUpdate("Save Scratch");
             //   string filename = AxiomIRISRibbon.Utility.SaveTempFile(_versionid);
                _doc.SaveAs2(FileName: strFileAttached, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent);

                //Save a copy!
                Globals.ThisAddIn.ProcessingUpdate("Save Copy");
                string filenamecopy =  AxiomIRISRibbon.Utility.SaveTempFile(_versionid + "X");
                Word.Document dcopy = Globals.ThisAddIn.Application.Documents.Add(strFileAttached, Visible: false);
                dcopy.SaveAs2(FileName: filenamecopy, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent);

                var docclose = (Microsoft.Office.Interop.Word._Document)dcopy;
                docclose.Close();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(docclose);

                //Now save the file - change this to always save as the version name

                Globals.ThisAddIn.ProcessingUpdate("Save To SalesForce");
                string vfilename = _versionName.Replace(" ", "_") + ".docx";
                dr = AxiomIRISRibbon.Utility.HandleData(_d.UpdateFile(_attachmentid, vfilename, filenamecopy));

            }
            Globals.ThisAddIn.AddSaveHandler(); // add it back in
            Globals.ThisAddIn.ProcessingStop("End");
            return true;
        }
        public DataReturn SaveCombinedDoc(string newAttachmentId, string fileAmendmentTemplatePath)
        {
            DataReturn dr = new DataReturn();
            try
            {
                string strFileAttached = fileAmendmentTemplatePath;
                //Save the Contract

                //  DataReturn dr;
                _doc = Globals.ThisAddIn.Application.ActiveDocument;

                //Remove the contract refrence and id from document before save as combined doc.
                //To avoid save as a template
                Globals.ThisAddIn.AddDocId(_doc, "", "", "");
                //End

                _doc.SaveAs2(FileName: strFileAttached, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent);
                string filenamecopy = AxiomIRISRibbon.Utility.SaveTempFile(_versionid + "Z");
                Word.Document dcopy = Globals.ThisAddIn.Application.Documents.Add(strFileAttached, Visible: false);
                dcopy.SaveAs2(FileName: filenamecopy, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent);

                var docclose = (Word._Document)dcopy;
                docclose.Close();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(docclose);

                string vfilename = _versionName.Replace(" ", "_") + ".docx";
                dr = AxiomIRISRibbon.Utility.HandleData(_d.UpdateFile(newAttachmentId, vfilename, filenamecopy));

                return dr;
            }
            catch (Exception ex)
            {
                return dr;
            }
        }
Example #13
0
        public string GetReport()
        {
            try
            {
                _wordApp = new Word.Application();
                _doc = _wordApp.Documents.Add(_templateWordPath);

                _doc.Bookmarks["Город"].Range.Text = City;
                _doc.Bookmarks["Дата"].Range.Text = Date.ToShortDateString();
                _doc.Bookmarks["ДатаДоговора"].Range.Text = ContractDate.ToShortDateString();
                _doc.Bookmarks["ДатаДоговора2"].Range.Text = ContractDate.ToShortDateString();
                _doc.Bookmarks["ДатаДоговора3"].Range.Text = ContractDate.ToShortDateString();
                _doc.Bookmarks["ДатаОкончания"].Range.Text = EndDate.ToShortDateString();
                _doc.Bookmarks["Директор"].Range.Text = Director;
                _doc.Bookmarks["Заказчик"].Range.Text = Customer;
                _doc.Bookmarks["ЗаказчикФИО"].Range.Text = CustomerFIO;
                _doc.Bookmarks["НомерДоговора"].Range.Text = ContractNumber.ToString();
                _doc.Bookmarks["НомерДоговора2"].Range.Text = ContractNumber.ToString();
                _doc.Bookmarks["НомерДоговора3"].Range.Text = ContractNumber.ToString();
                _doc.Bookmarks["ПаспортВыдан"].Range.Text = string.Format("{0} {1} г.", PassportIssuedBy, PassportIssuedDate.ToShortDateString());
                _doc.Bookmarks["ПаспортНомер"].Range.Text = PassportNumber;
                _doc.Bookmarks["ПаспортСерия"].Range.Text = PassportSeries;
                _doc.Bookmarks["Подрядчик"].Range.Text = Contractor;
                _doc.Bookmarks["ПодрядчикФИО"].Range.Text = ContractorFIO;
                _doc.Bookmarks["Работы"].Range.Text = Services;
                _doc.Bookmarks["ФактическаяДатаОкончания"].Range.Text = ActualEndDate.ToShortDateString();

                _doc.SaveAs2(FileName: _documnetSavePath, FileFormat: Word.WdSaveFormat.wdFormatPDF);

                return _documnetSavePath;
            }
            catch (Exception)
            {
            }
            finally
            {
                _doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                _wordApp.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
            }
            return null;
        }
Example #14
0
 public string GetReport()
 {
     try
     {
         _wordApp = new Word.Application();
         _doc = _wordApp.Documents.Add(_wordPath);
         _doc.Bookmarks["ГодРождения"].Range.Text = BirthDay.Year.ToString().Trim();
         _doc.Bookmarks["Гражданство"].Range.Text = Nationality;
         _doc.Bookmarks["ДатаЗачисления"].Range.Text = EnrollmentDate.ToShortDateString();
         _doc.Bookmarks["ДатаМесяцРождения"].Range.Text = BirthDay.Day + " " + GetMonthName(BirthDay.Month);
         _doc.Bookmarks["Должность"].Range.Text = JobPosition;
         _doc.Bookmarks["МедСправка"].Range.Text = "№" + MedicalNumber + " от " + MedicalDate.ToShortDateString() + ", " + MedicalName;
         _doc.Bookmarks["МестоРаботы"].Range.Text = Job;
         _doc.Bookmarks["МестоРождения"].Range.Text = BirthPlace;
         _doc.Bookmarks["Образование"].Range.Text = Education;
         _doc.Bookmarks["ОтФИО"].Range.Text = FIO;
         _doc.Bookmarks["ПаспортВыдан"].Range.Text = PassportIssueBy + " " + PassportIssueDate.ToShortDateString();
         _doc.Bookmarks["ПаспортСерия1"].Range.Text = PassportNumber.Substring(0, 2);
         _doc.Bookmarks["ПаспортСерия2"].Range.Text = PassportNumber.Substring(3, PassportNumber.Length - 3);
         _doc.Bookmarks["Программа"].Range.Text = Program;
         _doc.Bookmarks["Регистрация"].Range.Text = Registration;
         _doc.Bookmarks["ТелДом"].Range.Text = PhoneHome;
         _doc.Bookmarks["ТелМоб"].Range.Text = PhoneMobile;
         _doc.Bookmarks["ФИО"].Range.Text = LastName + " " + Name + " " + MiddleName;
         _doc.SaveAs2(FileName: _saveAsPath, FileFormat: Word.WdSaveFormat.wdFormatPDF);
     }
     catch (Exception)
     {
     }
     finally
     {
         _doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
         _wordApp.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
     }
     return _saveAsPath;
 }
Example #15
0
        internal void CreateWordDocument(object filename, object saveAs)
        {
            Word.Application wordApp = new Word.Application();

            object missing = Missing.Value;

            Word.Document myWordDoc = null;

            if (File.Exists((string)filename))
            {
                object readOnly  = false;
                object isVisible = false;
                wordApp.Visible = false;


                myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing, ref missing);


                myWordDoc.Activate();
                wordApp.Visible = false;

                //suche
                this.FindAndReplace(wordApp, "<vorMontag>", cbVorMontag.Text);
                this.FindAndReplace(wordApp, "<hauptMontag>", cbHauptMontag.Text);
                this.FindAndReplace(wordApp, "<nachMontag>", cbNachMontag.Text);

                this.FindAndReplace(wordApp, "<vorDienstag>", cbVorDienstag.Text);
                this.FindAndReplace(wordApp, "<hauptDienstag>", cbHauptDienstag.Text);
                this.FindAndReplace(wordApp, "<nachDienstag>", cbNachDienstag.Text);

                this.FindAndReplace(wordApp, "<vorMittwoch>", cbVorMittwoch.Text);
                this.FindAndReplace(wordApp, "<hauptMittwoch>", cbHauptMittwoch.Text);
                this.FindAndReplace(wordApp, "<nachMittwoch>", cbNachMittwoch.Text);

                this.FindAndReplace(wordApp, "<vorDonnerstag>", cbVorDonnerstag.Text);
                this.FindAndReplace(wordApp, "<hauptDonnerstag>", cbHauptDonnerstag.Text);
                this.FindAndReplace(wordApp, "<nachDonnerstag>", cbNachDonnerstag.Text);

                this.FindAndReplace(wordApp, "<vorFreitag>", cbVorFreitag.Text);
                this.FindAndReplace(wordApp, "<hauptFreitag>", cbHauptFreitag.Text);
                this.FindAndReplace(wordApp, "<nachFreitag>", cbNachFreitag.Text);

                this.FindAndReplace(wordApp, "<datum>", DateTime.Now.ToShortDateString());
            }
            else
            {
                MessageBox.Show("Dokument konnte nicht gefunden werden");
            }

            ////Speichern
            myWordDoc.SaveAs2(ref saveAs, ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing);

            DialogResult dialogResult = MessageBox.Show("Der Speiseplan wurde angelegt,\nsoll dieser direkt geöffnet werden?", "", MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.Yes)
            {
                wordApp.Visible = true;
            }
            else if (dialogResult == DialogResult.No)
            {
                myWordDoc.Close();
                wordApp.Quit();
            }
        }
Example #16
0
        public static bool CreateWordsDocuments(object docPath, string savaAs, string docName, DataRowView[] candidats, string presedinte, string membru1, string membru2)
        {
            int candiLength = candidats.Length;
            Console.WriteLine("LENGTH" + candiLength);

            object missing = Missing.Value;
            //      Word.Document[] adocs = new Word.Document[candidats.Length];

            Word.Document aDoc = null;
            Word.Application wordApp = null;

            try{
                for (int i = 0; i < candiLength; ++i)
                {

                    aDoc = new Word.Document();
                    wordApp = new Word.Application();
                    DataRow candidat = candidats[i].Row;
                    List<int> processesbeforegen = getRunningProcesses();
                    string savePath =(string) savaAs + docName + " " + candidat["Nume"] + "_" + candidat["Prenume"] ;

                    if (File.Exists((string)docPath))
                    {
                        Console.WriteLine("Fajlnal vagyok");

                        object readOnly = false; //default
                        object isVisible = false;

                        wordApp.Visible = false;

                        aDoc = wordApp.Documents.Open(ref docPath, ref missing, ref readOnly,
                                                    ref missing, ref missing, ref missing,
                                                    ref missing, ref missing, ref missing,
                                                    ref missing, ref missing, ref missing,
                                                    ref missing, ref missing, ref missing, ref missing);

                        aDoc.Activate();

                        Console.WriteLine("megnyitva");

                        //Find and replace:
                        FindAndReplace(wordApp, "{NrMatricol}", candidat["NrMatricol"]);
                        FindAndReplace(wordApp, "{Nume}", candidat["Nume"]);
                        FindAndReplace(wordApp, "{Prenume}", candidat["Prenume"]);
                        FindAndReplace(wordApp, "{Tata}", candidat["Tata"]);
                        FindAndReplace(wordApp, "{Mama}", candidat["Mama"]);
                        FindAndReplace(wordApp, "{CNP>", candidat["CNP"]);
                        FindAndReplace(wordApp, "{DataNasterii}", candidat["DataNasterii"]);
                        FindAndReplace(wordApp, "{LoculNasterii}", candidat["LoculNasterii"]);
                        FindAndReplace(wordApp, "{Strada}", candidat["Strada"]);
                        FindAndReplace(wordApp, "{Nr}", candidat["Nr"]);
                        FindAndReplace(wordApp, "{Bloc}", candidat["Bloc"]);
                        FindAndReplace(wordApp, "{Scara}", candidat["Scara"]);
                        FindAndReplace(wordApp, "{Ap}", candidat["Ap"]);
                        FindAndReplace(wordApp, "{Localitate}", candidat["Localitate"]);
                        FindAndReplace(wordApp, "{Judet}", candidat["Judet"]);
                        FindAndReplace(wordApp, "{Cp}", candidat["Cp"]);
                        FindAndReplace(wordApp, "{Telefon}", candidat["Telefon"]);
                        FindAndReplace(wordApp, "{Studii}", candidat["Studii"]);
                        FindAndReplace(wordApp, "{Profesia}", candidat["Profesia"]);
                        FindAndReplace(wordApp, "{LocMunca}", candidat["LocMunca"]);
                        FindAndReplace(wordApp, "{Presedinte}", presedinte);
                        FindAndReplace(wordApp, "{Membru1}", membru1);
                        FindAndReplace(wordApp, "{Membru2}", membru2);

                        Console.WriteLine("cserelgetes");

                        object saveFullPath = savePath;

                        aDoc.SaveAs2(ref saveFullPath, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing);

                        //Close Document:

                        aDoc.Close(ref missing, ref missing, ref missing);
                        wordApp.Quit(false);

                        Marshal.FinalReleaseComObject(wordApp);

                        aDoc = null;
                        wordApp = null;
                        List<int> processesaftergen = getRunningProcesses();
                        Console.WriteLine("COUNT > " + processesbeforegen.Count + "  " + processesaftergen.Count);
                        killProcesses(processesbeforegen, processesaftergen);
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("file dose not exist.");
                        return false;
                    }
                }

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Error occured at Report!\n"+ex.Message);
                return false;
            }
            finally
            {
                if (aDoc != null) aDoc.Close(ref missing, ref missing, ref missing);
                if (wordApp != null)
                {
                    wordApp.Quit(ref missing, ref missing, ref missing);
                    Marshal.FinalReleaseComObject(wordApp);
                }

            }

            return true;
        }
Example #17
0
        public void Export_Data_To_Word(DataGridView DGV, string filename)
        {
            if (DGV.Rows.Count != 0)
            {
                int RowCount    = DGV.Rows.Count;
                int ColumnCount = DGV.Columns.Count;
                Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

                //add rows
                int r = 0;
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    for (r = 0; r <= RowCount - 1; r++)
                    {
                        DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
                    } //end row loop
                }     //end column loop

                Word.Document oDoc = new Word.Document();
                oDoc.Application.Visible = true;
                //page orintation
                oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
                dynamic oRange = oDoc.Content.Application.Selection.Range;
                string  oTemp  = "";
                for (r = 0; r <= RowCount - 1; r++)
                {
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        oTemp = oTemp + DataArray[r, c] + "\t";
                    }
                }
                //table format
                oRange.Text = oTemp;
                object Separator       = Word.WdTableFieldSeparator.wdSeparateByTabs;
                object ApplyBorders    = true;
                object AutoFit         = true;
                object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;

                oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,
                                      Type.Missing, Type.Missing, ref ApplyBorders,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);
                oRange.Select();
                oDoc.Application.Selection.Tables[1].Select();
                oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
                oDoc.Application.Selection.Tables[1].Rows.Alignment             = 0;
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.InsertRowsAbove(1);
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                //header row style
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold      = 1;
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Times New Roman";
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;
                //add header row manually
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
                }
                //table style
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                //header text
                foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)
                {
                    Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
                    headerRange.Text      = "ТУТ ТИТУЛ";
                    headerRange.Font.Size = 16;
                    headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                }
                //save the file
                oDoc.SaveAs2(filename);
            }
        }
Example #18
0
        //Creeate the Doc Method
        private void CreateWordDocument(object filename, object SaveAs, String usnpass, String tdate)
        {
            Word.Application wordApp = new Word.Application();
            object           missing = Missing.Value;

            Word.Document myWordDoc = null;

            if (File.Exists((string)filename))
            {
                object readOnly  = false;
                object isVisible = false;
                wordApp.Visible = false;

                myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing, ref missing);
                myWordDoc.Activate();
                MySqlConnection con = new MySqlConnection("server = localhost; user id = root;  password = redhat; persistsecurityinfo = True; database = dbproject");

                con.Open();

                MySqlCommand    cmd = new MySqlCommand("Select * from student where usn='" + usnpass + "'", con);
                MySqlDataReader rdusn = cmd.ExecuteReader();
                String          tbname, tbsem, tbbranch;
                if (rdusn.Read())
                {
                    tbname   = (rdusn["name"].ToString());
                    tbsem    = (rdusn["semester"].ToString());
                    tbbranch = (rdusn["branch"].ToString());
                }
                else
                {
                    MessageBox.Show("Incorrect USN, corresponding student record not found!");
                    tbname   = "";
                    tbsem    = "";
                    tbbranch = "";
                }
                con.Close();
                //find and replace
                String sem = tbsem;
                String ext;
                if (sem == "1")
                {
                    ext = "st";
                }
                else if (sem == "2")
                {
                    ext = "nd";
                }
                else if (sem == "3")
                {
                    ext = "rd";
                }
                else
                {
                    ext = "th";
                }
                this.FindAndReplace(wordApp, "<name>", tbname.ToString());
                this.FindAndReplace(wordApp, "<semester>", tbsem + ext + " Semester");
                this.FindAndReplace(wordApp, "<branch>", tbbranch);
                this.FindAndReplace(wordApp, "<event>", tbcat.Text + " tournament");
                this.FindAndReplace(wordApp, "<date>", tdate.ToString());
                this.FindAndReplace(wordApp, "<acadyear>", DateTime.Now.Year + "-" + Convert.ToString(DateTime.Now.Year + 1));
            }
            else
            {
                MessageBox.Show("File not Found!");
            }

            //Save as
            myWordDoc.SaveAs2(ref SaveAs, ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing);

            myWordDoc.Close();
            wordApp.Quit();
            MessageBox.Show("File Created!");
        }
        private void PrintToWordDocument()
        {
            Word.Application objWord = new Word.Application();
            objWord.Visible     = true;
            objWord.WindowState = Word.WdWindowState.wdWindowStateNormal;

            Word.Document objDoc = objWord.Documents.Add();

            var objPara = objDoc.Paragraphs.Add();

            objPara.Range.Font.Name = "Calibri";
            objPara.Range.Font.Size = 18;
            objPara.Range.Text      = "Bestellingen\nDat betaal ik zelf wel.";
            objPara.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            objPara.Range.InsertParagraphAfter();

            string leverancierNaam = "";
            int    bestellingId    = 0;

            using (BestellingenDatabaseEntities ctx = new BestellingenDatabaseEntities())
            {
                var leveranciers    = ctx.Leveranciers.Where(x => x.LeverancierID == (int)cbLeverancier.SelectedValue).FirstOrDefault();
                var leverancierPara = objDoc.Paragraphs.Add();
                leverancierPara.Range.Font.Name = "Calibri";
                leverancierPara.Range.Font.Size = 12;
                leverancierPara.Range.Text      = leveranciers.Contactpersoon + "\n" + leveranciers.Straatnaam + " " + leveranciers.Huisnummer + "Bus " + leveranciers.Bus + "\n" + leveranciers.Postcode + " " + leveranciers.Gemeente;
                leverancierPara.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                leverancierPara.Range.InsertParagraphAfter();

                leverancierNaam = leveranciers.Contactpersoon;

                Word.InlineShape line1 = objDoc.Paragraphs.Last.Range.InlineShapes.AddHorizontalLineStandard();
                line1.Height = 2;
                line1.Fill.Solid();
                line1.HorizontalLineFormat.NoShade      = true;
                line1.Fill.ForeColor.RGB                = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
                line1.HorizontalLineFormat.PercentWidth = 100;
                line1.HorizontalLineFormat.Alignment    = WdHorizontalLineAlignment.wdHorizontalLineAlignCenter;

                var tableHeader = objDoc.Paragraphs.Add();
                tableHeader.Range.Font.Name = "Calibri";
                tableHeader.Range.Font.Size = 12;
                tableHeader.Range.Text      = "Artikel\t\t\t\t Aantal\tPrijs per stuk\tBTW   Prijs excl. BTW\tPrijs incl. BTW";
                tableHeader.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                tableHeader.Range.InsertParagraphAfter();

                Word.InlineShape line2 = objDoc.Paragraphs.Last.Range.InlineShapes.AddHorizontalLineStandard();
                line2.Height = 2;
                line2.Fill.Solid();
                line2.HorizontalLineFormat.NoShade      = true;
                line2.Fill.ForeColor.RGB                = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
                line2.HorizontalLineFormat.PercentWidth = 100;
                line2.HorizontalLineFormat.Alignment    = WdHorizontalLineAlignment.wdHorizontalLineAlignCenter;

                var leverancierBestelling = ctx.Bestellings.Where(b => b.LeverancierID != null);
                bestellingId = leverancierBestelling.Max(x => x.BestellingID);

                var bestelling = ctx.BestellingProducts.Where(x => x.BestellingID == bestellingId).ToList();

                var tablePara = objDoc.Paragraphs.Add();
                tablePara.Range.Font.Name = "Calibri";
                tablePara.Range.Font.Size = 12;

                string  tableContent = "";
                decimal totaal       = 0;

                foreach (BestellingProduct item in bestelling)
                {
                    var    product     = ctx.Products.Where(p => p.ProductID == item.ProductID).FirstOrDefault();
                    string productNaam = "";
                    if (product.Naam.Trim().Length <= 7)
                    {
                        productNaam = product.Naam + "\t\t\t\t";
                    }
                    else if (product.Naam.Trim().Length > 7 && product.Naam.Trim().Length < 14)
                    {
                        productNaam = product.Naam + "\t\t\t";
                    }

                    decimal actualPrijs       = Convert.ToDecimal(product.Inkoopprijs) + Convert.ToDecimal(product.Marge);
                    decimal prijsInclBtw      = Convert.ToDecimal(item.Aantal) * actualPrijs;
                    decimal prijsExclBtw      = Math.Round(prijsInclBtw - (prijsInclBtw * (Convert.ToDecimal(product.BTW) / 100)), 2);
                    string  prijsExclBtwValue = prijsExclBtw.ToString() + "\t";
                    totaal += prijsInclBtw;

                    string prijsPerStuckValue = actualPrijs.ToString();
                    if (prijsPerStuckValue.Trim().Length > 3)
                    {
                        prijsPerStuckValue += "\t";
                    }
                    else
                    {
                        prijsPerStuckValue += "\t\t";
                    }

                    tableContent += productNaam + "   " + item.Aantal + "\t  €" + prijsPerStuckValue + product.BTW + "\t€" + prijsExclBtwValue + "€" + prijsInclBtw + "\n";
                }
                tablePara.Range.Text = tableContent;

                tablePara.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                tablePara.Range.InsertParagraphAfter();

                Word.InlineShape line3 = objDoc.Paragraphs.Last.Range.InlineShapes.AddHorizontalLineStandard();
                line3.Height = 2;
                line3.Fill.Solid();
                line3.HorizontalLineFormat.NoShade      = true;
                line3.Fill.ForeColor.RGB                = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
                line3.HorizontalLineFormat.PercentWidth = 100;
                line3.HorizontalLineFormat.Alignment    = WdHorizontalLineAlignment.wdHorizontalLineAlignCenter;


                var footerPara = objDoc.Paragraphs.Add();
                footerPara.Range.Font.Name = "Calibri";
                footerPara.Range.Font.Size = 12;
                footerPara.Range.Text      = "Totaal\t    €" + totaal + "\t\t";
                footerPara.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
                footerPara.Range.InsertParagraphAfter();

                string filePath = "C:\\Users\\Krëfel\\source\\repos\\TussentijdsProject\\TussentijdsProject\\bin\\Debug\\";
                string fileName = filePath + leverancierNaam + " " + DateTime.Now.ToString("dd-MM-yyyy") + " " + "(" + bestellingId.ToString() + ")" + ".docx";
                objDoc.SaveAs2(fileName);
                objDoc.Close();
                objWord.Quit();
            }
        }
Example #20
0
        //Methode for create Document
        private void createWordDocument(object filename, object SaveAs)
        {
            Word.Application wordApp = new Word.Application();
            object           missing = Missing.Value;

            Word.Document MyWordDoc = null;

            if (File.Exists((string)filename))
            {
                DateTime today     = DateTime.Now;
                object   readOnly  = false;
                object   isVisible = false;
                wordApp.Visible = false;

                MyWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing);

                MyWordDoc.Activate();

                //FindAndReplace

                this.FindAndReplace(wordApp, "<texto0>", txtContProElec.Text);
                this.FindAndReplace(wordApp, "<texto0>", txtContProMec.Text);
                this.FindAndReplace(wordApp, "<proyecto>", txtNomProElec.Text);
                this.FindAndReplace(wordApp, "<proyecto>", txtNomProMec.Text);
                this.FindAndReplace(wordApp, "<locacion>", txtUbProElec.Text);
                this.FindAndReplace(wordApp, "<locacion>", txtUbProMec.Text);
                this.FindAndReplace(wordApp, "<atencion>", txtAtenElec.Text);
                this.FindAndReplace(wordApp, "<atencion>", txtAtenMec.Text);
                this.FindAndReplace(wordApp, "<asunto>", txtAsunElec.Text);
                this.FindAndReplace(wordApp, "<asunto>", txtAsunMec.Text);
                this.FindAndReplace(wordApp, "<proyec_num>", txtProyNumElec.Text);
                this.FindAndReplace(wordApp, "<proyec_num>", txtProyNumMec.Text);
                this.FindAndReplace(wordApp, "<Ingeniero1>", txtIng1.Text);
                this.FindAndReplace(wordApp, "<Ingeniero2>", txtIng2.Text);
                this.FindAndReplace(wordApp, "<MailIng1>", txtMail1.Text);
                this.FindAndReplace(wordApp, "<MailIng2>", txtMail2.Text);
                this.FindAndReplace(wordApp, "<titulo1>", txtTit1.Text);
                this.FindAndReplace(wordApp, "<Texto1>", Rtxt1.Text);
                this.FindAndReplace(wordApp, "<titulo2>", txtTit2.Text);
                this.FindAndReplace(wordApp, "<Texto2>", Rtxt2.Text);
                this.FindAndReplace(wordApp, "<titulo3>", txtTit3.Text);
                this.FindAndReplace(wordApp, "<Texto3>", Rtxt3.Text);
                this.FindAndReplace(wordApp, "<titulo4>", txtTit4.Text);
                this.FindAndReplace(wordApp, "<Texto4>", Rtxt4.Text);
                this.FindAndReplace(wordApp, "<titulo5>", txtTit5.Text);
                this.FindAndReplace(wordApp, "<Texto5>", Rtxt5.Text);
                this.FindAndReplace(wordApp, "<titulo6>", txtTit6.Text);
                this.FindAndReplace(wordApp, "<Texto6>", Rtxt6.Text);
                this.FindAndReplace(wordApp, "<titulo7>", txtTit7.Text);
                this.FindAndReplace(wordApp, "<Texto7>", Rtxt7.Text);
                this.FindAndReplace(wordApp, "<titulo8>", txtTit8.Text);
                this.FindAndReplace(wordApp, "<Texto8>", Rtxt8.Text);
                this.FindAndReplace(wordApp, "<titulo9>", txtTit9.Text);
                this.FindAndReplace(wordApp, "<Texto9>", Rtxt9.Text);
                this.FindAndReplace(wordApp, "<titulo10>", txtTit10.Text);
                this.FindAndReplace(wordApp, "<Texto10>", Rtxt10.Text);
                this.FindAndReplace(wordApp, "<titulo11>", txtTit11.Text);
                this.FindAndReplace(wordApp, "<Texto11>", Rtxt11.Text);
                this.FindAndReplace(wordApp, "<titulo12>", txtTit12.Text);
                this.FindAndReplace(wordApp, "<Texto12>", Rtxt12.Text);
                this.FindAndReplace(wordApp, "<fecha>", DateTime.Now.ToShortDateString());

                //                Insert Image
                //Image img = resizeImage(pathImage, new Size(200, 90));
            }
            else
            {
                MessageBox.Show("No existe el archivo");
                return;
            }


            //Save AS
            MyWordDoc.SaveAs2(ref SaveAs, ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing);
            //Clse
            MyWordDoc.Close();
            wordApp.Quit();
            MessageBox.Show("Documento Creado");
        }
Example #21
0
        public string GetReport()
        {
            try
            {
                _wordApp = new Word.Application();
                _doc = _wordApp.Documents.Add(_wordPath);
                _doc.Bookmarks["ДатаЗачисления"].Range.Text = EnrollmentDate.ToShortDateString();
                _doc.Bookmarks["ДатаЗачисления2"].Range.Text = EnrollmentDate.ToShortDateString();
                _doc.Bookmarks["ДатаРождения"].Range.Text = BirthDay.ToShortDateString();
                _doc.Bookmarks["ИдентификационныйНомер"].Range.Text = PassportNumberId;
                _doc.Bookmarks["КатегорияТС"].Range.Text = Program;
                _doc.Bookmarks["МестоРождения"].Range.Text = BirthPlace;
                _doc.Bookmarks["НачалоОбучения"].Range.Text = StartDate.ToShortDateString();
                _doc.Bookmarks["НомерДоговора"].Range.Text = ContractNumber.ToString();
                _doc.Bookmarks["ПаспортДатаВыдачи"].Range.Text = PassportIssueDate.ToShortDateString();
                _doc.Bookmarks["ПаспортКемВыдан"].Range.Text = PassportIssueBy;
                _doc.Bookmarks["ПаспортСерияНомер"].Range.Text = PassportNumber;
                _doc.Bookmarks["ПостояннаяРегистрация"].Range.Text = Registration;
                _doc.Bookmarks["ПрактикаЧасов"].Range.Text = PracticeHours.ToString();
                _doc.Bookmarks["ПрограммаОбучения"].Range.Text = Program;
                _doc.Bookmarks["Продолжительность"].Range.Text = (PracticeHours + TheoryHours).ToString();
                _doc.Bookmarks["СтоимостьОбучения"].Range.Text = Cost.ToString();
                _doc.Bookmarks["ТелефонСот"].Range.Text = PhoneMobile;
                _doc.Bookmarks["ТеорияЧасов"].Range.Text = TheoryHours.ToString();
                _doc.Bookmarks["ТипГруппы"].Range.Text = GroupType;
                _doc.Bookmarks["ФИОкурсанта"].Range.Text = LastName + " " + Name + " " + MiddleName;
                _doc.Bookmarks["ФИОкурсанта2"].Range.Text = LastName + " " + Name + " " + MiddleName;

                _doc.SaveAs2(FileName: _saveAsPath, FileFormat: Word.WdSaveFormat.wdFormatPDF);

            }
            catch (Exception)
            {
            }
            finally
            {
                _doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                _wordApp.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
            }
            return _saveAsPath;
        }
Example #22
0
        //Creeate the Doc Method
        private void CreateWordDocument(object filename, object SaveAs)
        {
            Word.Application wordApp = new Word.Application();
            object           missing = Missing.Value;

            Word.Document myWordDoc = null;

            if (File.Exists((string)filename))
            {
                object readOnly  = false;
                object isVisible = false;
                wordApp.Visible = false;

                myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing, ref missing);
                myWordDoc.Activate();
                Word.Table      gc  = myWordDoc.Tables[1];
                MySqlConnection con = new MySqlConnection("server = localhost; user id = root;  password = redhat; persistsecurityinfo = True; database = dbproject");

                con.Open();

                MySqlCommand    cmd   = new MySqlCommand("Select * from student where usn='" + tbusn.Text + "'", con);
                MySqlDataReader rdusn = cmd.ExecuteReader();
                if (rdusn.Read())
                {
                    String name   = (rdusn["name"].ToString());
                    String sem    = (rdusn["semester"].ToString());
                    String branch = (rdusn["branch"].ToString());

                    this.FindAndReplace(wordApp, "<name>", name);
                    this.FindAndReplace(wordApp, "<sem>", tbsem.Text);
                    this.FindAndReplace(wordApp, "<branch>", branch);
                    this.FindAndReplace(wordApp, "<usn>", tbusn.Text);
                }
                else
                {
                    MessageBox.Show("Incorrect USN or wrong query!");
                }
                rdusn.Close();
                int             crow   = 2;
                int             ccol   = 2;
                int             gcol   = 5;
                int             gpcol  = 6;
                int             i      = 0;
                double[]        tgp    = new double[5];
                MySqlCommand    cmd1   = new MySqlCommand("Select * from academics,course where course.course_code=academics.course_code and usn='" + tbusn.Text + "'", con);
                MySqlDataReader rdusn1 = cmd1.ExecuteReader();
                while (rdusn1.Read())
                {
                    double[] test = new double[3];
                    test[0] = Convert.ToInt32((rdusn1["test1"].ToString()));
                    test[1] = Convert.ToInt32((rdusn1["test2"].ToString()));
                    test[2] = Convert.ToInt32((rdusn1["test3"].ToString()));
                    Array.Sort(test);

                    double cie    = test[2] + test[1];
                    double semend = Convert.ToInt32((rdusn1["sem_end"].ToString()));
                    double score  = cie + semend / 2;
                    String grade;
                    int    gp;
                    if (cie < 25)
                    {
                        grade = "F";
                        gp    = 0;
                    }
                    else
                    {
                        if (score <= 100 && score >= 90)
                        {
                            grade = "S";
                            gp    = 10;
                        }
                        else if (score < 90 && score >= 75)
                        {
                            grade = "A";
                            gp    = 9;
                        }
                        else if (score < 75 && score >= 60)
                        {
                            grade = "B";
                            gp    = 8;
                        }
                        else if (score < 60 && score >= 50)
                        {
                            grade = "C";
                            gp    = 7;
                        }
                        else if (score < 50 && score >= 40)
                        {
                            grade = "D";
                            gp    = 6;
                        }
                        else
                        {
                            grade = "F";
                            gp    = 0;
                        }
                    }

                    tgp[i] = gp;
                    i++;
                    String course   = (rdusn1["course_code"].ToString());
                    String coursenm = (rdusn1["course_name"].ToString());
                    gc.Cell(crow, ccol).Range.Text     = course;
                    gc.Cell(crow, ccol + 1).Range.Text = coursenm;
                    gc.Cell(crow, gcol).Range.Text     = grade;
                    gc.Cell(crow, gpcol).Range.Text    = gp.ToString();

                    crow++;
                }

                double sgpa = (tgp.Sum()) * 4 / 20;
                this.FindAndReplace(wordApp, "<sgpa>", sgpa.ToString());

                con.Close();
            }
            else
            {
                MessageBox.Show("File not Found!");
            }

            //Save as
            myWordDoc.SaveAs2(ref SaveAs, ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing);

            myWordDoc.Close();
            wordApp.Quit();
            MessageBox.Show("File Created!");
        }
Example #23
0
        public string GetReport()
        {
            try
            {
                _wordApp = new Word.Application();
                _doc = _wordApp.Documents.Add(_templateWordPath);

                _doc.Bookmarks["Арендатор"].Range.Text = Renter;
                _doc.Bookmarks["АрендаторФИО"].Range.Text = RenterFIO;
                _doc.Bookmarks["Арендодатель"].Range.Text = LandLord;
                _doc.Bookmarks["АрендодательФИО"].Range.Text = Director;
                _doc.Bookmarks["Город"].Range.Text = City;
                _doc.Bookmarks["ГосНомер1"].Range.Text = TransportRegNumber;
                _doc.Bookmarks["ГосНомер2"].Range.Text = TransportRegNumber;
                _doc.Bookmarks["Дата"].Range.Text = Date.ToShortDateString();
                _doc.Bookmarks["ДатаДоговора"].Range.Text = ContractDate.ToShortDateString();
                _doc.Bookmarks["Директор"].Range.Text = LandLordFIO;
                _doc.Bookmarks["Номер"].Range.Text = Number.ToString();
                _doc.Bookmarks["Транспорт1"].Range.Text = TransportName;
                _doc.Bookmarks["Транспорт2"].Range.Text = TransportName;

                _doc.SaveAs2(FileName: _documnetSavePath, FileFormat: Word.WdSaveFormat.wdFormatPDF);

                return _documnetSavePath;
            }
            catch (Exception)
            {
            }
            finally
            {
                _doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                _wordApp.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
            }
            return null;
        }
Example #24
0
        public void Kadr_UchetWord()
        {
            word.Application application = new word.Application();
            word.Document    document    = application.Documents.Add(Visible: true);
            word.Range       range       = document.Range(0, 0);
            string           file_name   = Registry_Class.DirPath + "\\КУ_"
                                           + DateTime.Now.ToString("_hh_mm_ss_dd_MM_yyyy") + ".docx";

            try
            {
                document.Sections.PageSetup.LeftMargin
                    = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocLM));
                document.Sections.PageSetup.RightMargin
                    = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocRM));
                document.Sections.PageSetup.TopMargin
                    = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocTM));
                document.Sections.PageSetup.BottomMargin
                    = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocBM));
                range.ParagraphFormat.Alignment
                    = word.WdParagraphAlignment.wdAlignParagraphCenter;
                range.ParagraphFormat.SpaceAfter      = 1;
                range.ParagraphFormat.SpaceBefore     = 1;
                range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle;
                range.Font.Name = "Times New Roman";
                range.Font.Size = 12;
                document.Paragraphs.Add();
                document.Paragraphs.Add();
                word.Paragraph Name_Doc = document.Paragraphs.Add();
                Name_Doc.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                Name_Doc.Range.Font.Name  = "Times New Roman";
                Name_Doc.Range.Font.Size  = 16;
                Name_Doc.Range.Text       = "КАДРОВЫЙ УЧЕТ";
                document.Paragraphs.Add();
                document.Paragraphs.Add();
                document.Paragraphs.Add();
                word.Paragraph pTable  = document.Paragraphs.Add();
                word.Table     tbCheck = document.Tables.Add(pTable.Range, table.Rows.Count + 1,
                                                             table.Columns.Count);

                tbCheck.Borders.InsideLineStyle  = word.WdLineStyle.wdLineStyleSingle;
                tbCheck.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle;
                tbCheck.Cell(1, 1).Range.Text    = "Код сотрудника";
                tbCheck.Cell(1, 2).Range.Text    = "Код табеля ЗП";
                tbCheck.Cell(1, 3).Range.Text    = "Код прибыли и расходов";
                tbCheck.Range.Font.Size          = 11;
                tbCheck.Range.Font.Name          = "Times New Roman";
                tbCheck.Columns[1].AutoFit();
                for (int i = 2; i <= tbCheck.Rows.Count; i++)
                {
                    for (int j = 1; j <= tbCheck.Columns.Count; j++)
                    {
                        tbCheck.Cell(i, j).Range.Text = table.Rows[i - 2][j - 1].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                Registry_Class.error_message += "\n"
                                                + DateTime.Now.ToLongDateString() + " " + ex.Message;
            }
            finally
            {
                document.SaveAs2(file_name, word.WdSaveFormat.wdFormatDocumentDefault);
                document.Close();
                application.Quit();
            }
        }
Example #25
0
        private void ProcessIntoMultipleFiles(string fileNameTemplate)
        {
            var    firstpage  = mandateData[0];
            string projtitle  = firstpage["[@PROJECTVARIATION-ProjectTitle]"];
            string varacronym = firstpage["[@PROJECTVARIATION-Acronym]"];

            string nameTemplate = projtitle + "-" + varacronym + "-{0}";
            string nameTo       = nameTemplate + ".docx";
            string nameToPDF    = nameTemplate + ".pdf";

            MSWord.Document docNew = null;

            SetStatus("Choose output folder");
            string outputFolder;

            using (var fbd = new FolderBrowserDialog())
            {
                DialogResult result = fbd.ShowDialog();
                if (result != DialogResult.OK || string.IsNullOrWhiteSpace(fbd.SelectedPath))
                {
                    return;
                }
                outputFolder = fbd.SelectedPath;
            }

            string fileNameTo    = outputFolder + "\\" + nameTo;
            string fileNameToPDF = outputFolder + "\\" + nameToPDF;

            SetStatus("Preparing MS Word");
            var winword = new MSWord.Application();

            winword.ShowAnimation = false;
            winword.Visible       = true;
            object missing = System.Reflection.Missing.Value;

            try
            {
                int n = 1;
                foreach (var pageData in mandateData)
                {
                    string partner = pageData["[@PARTNER-acronym]"];

                    SetStatus("Creating mandate: " + "[" + n.ToString() + "/" + mandateData.Count() + "]" + pageData["[@PARTNER-legal-name]"]);

                    docNew = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                    InsertDataPage(ref winword, ref docNew, fileNameTemplate, pageData, true);

                    docNew.SaveAs(String.Format(fileNameTo, partner));
                    docNew.SaveAs2(String.Format(fileNameToPDF, partner), MSWord.WdSaveFormat.wdFormatPDF);
                    docNew.Close();
                    docNew = null;

                    n++;
                }
                SetStatus("Done");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            finally
            {
                if (docNew != null)
                {
                    docNew.Close();
                }

                if (winword != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(winword);
                }

                winword = null;

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            SetStatus("");
        }
        public void ExportToWord(MainPageModelRACAPVM cases, int userId, int Assid)
        {
            string FileName = "";

            if (cases.RACAPCaseViewModel != null)
            {
                if (cases.RACAPCaseViewModel.RACAP_Correspondence_Type_Id == 1)
                {
                    FileName = "General_letter_English";
                }
                if (cases.RACAPCaseViewModel.RACAP_Correspondence_Type_Id == 2)
                {
                    FileName = "Reminder_letter_English";
                }
                if (cases.RACAPCaseViewModel.RACAP_Correspondence_Type_Id == 3)
                {
                    FileName = "Fault_letter_English";
                }
                if (cases.RACAPCaseViewModel.RACAP_Correspondence_Type_Id == 4)
                {
                    FileName = "Acknowledgment_letter_English";
                }
                if (cases.RACAPCaseViewModel.RACAP_Correspondence_Type_Id == 5)
                {
                    FileName = "Cover_letter_English";
                }
                if (cases.RACAPCaseViewModel.RACAP_Correspondence_Type_Id == 6)
                {
                    FileName = "Home_Affairs_letter_English";
                }
                if (cases.RACAPCaseViewModel.RACAP_Correspondence_Type_Id == 7)
                {
                    FileName = "Enquiries_letter_English";
                }
                if (cases.RACAPCaseViewModel.RACAP_Correspondence_Type_Id == 8)
                {
                    FileName = "Regret_letter_English";
                }


                string savePath     = ("C:/Users/hermanb.MAIL1/Documents/Visual Studio 2015/Projects/SDIIS (2)/SDIIS_Latest/SDIIS/RACAP_Module/App_Data/" + Assid + FileName + ".doc");
                string templatePath = ("C:\\Users\\hermanb.MAIL1\\Documents\\Visual Studio 2015\\Projects\\SDIIS (2)\\SDIIS_Latest\\SDIIS\\RACAP_Module\\App_Data\\" + FileName + ".dot");
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    doc = new Microsoft.Office.Interop.Word.Document();
                doc = app.Documents.Open(templatePath);
                doc.Activate();

                int?ChildPersonIDForCHildName = (from c in dbF.RACAP_Prospective_Parent
                                                 join d in dbF.RACAP_Matches on c.RACAP_Prospective_Parent_Id equals d.RACAP_Prospective_Parent_Id
                                                 join e in dbF.RACAP_Adoptive_Child on d.RACAP_Adoptive_Child_Id equals e.RACAP_Adoptive_Child_Id
                                                 join f in dbF.RACAP_Case_Details on e.RACAP_Case_Id equals f.RACAP_Case_Id
                                                 join g in dbF.Intake_Assessments on f.Intake_Assessment_Id equals g.Intake_Assessment_Id
                                                 join h in dbF.Clients on g.Client_Id equals h.Client_Id

                                                 where c.Intake_Assessment_Id == Assid
                                                 select h.Person_Id).FirstOrDefault();
                int?ParentPersonIdForClientName = (from i in dbF.Intake_Assessments
                                                   join h in dbF.Clients on i.Client_Id equals h.Client_Id
                                                   where i.Intake_Assessment_Id == Assid
                                                   select h.Person_Id).FirstOrDefault();



                if (doc.Bookmarks.Exists("ClientName") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null)
                {
                    doc.Bookmarks["ClientName"].Range.Text = dbF.Persons.Find(ParentPersonIdForClientName).First_Name + " " + dbF.Persons.Find(ParentPersonIdForClientName).Last_Name;
                }
                if (doc.Bookmarks.Exists("CHildName") && ChildPersonIDForCHildName != 0 && ChildPersonIDForCHildName != null)
                {
                    doc.Bookmarks["CHildName"].Range.Text = dbF.Persons.Find(ChildPersonIDForCHildName).First_Name + " " + dbF.Persons.Find(ChildPersonIDForCHildName).Last_Name;
                }
                if (doc.Bookmarks.Exists("CHildID") && ChildPersonIDForCHildName != 0 && ChildPersonIDForCHildName != null)
                {
                    doc.Bookmarks["CHildID"].Range.Text = dbF.Persons.Find(ChildPersonIDForCHildName).Identification_Number;
                }

                AddressModel GetAdd = new AddressModel();
                PersonModel  GetPer = new PersonModel();

                var Add       = dbF.Persons.Find(ParentPersonIdForClientName).Addresses.FirstOrDefault();
                int AddressId = Add.Address_Id;
                int PerSonId  = (from a in dbF.Intake_Assessments
                                 join b in dbF.Clients on a.Client_Id equals b.Client_Id
                                 join c in dbF.Persons on b.Person_Id equals c.Person_Id
                                 where a.Intake_Assessment_Id == Assid
                                 select c.Person_Id).FirstOrDefault();
                bool AddressCheck = false;
                if (AddressId > 0 && dbF.Addresses.Find(AddressId).Address_Line_1 != null)
                {
                    AddressCheck = true;
                }
                else
                {
                    AddressCheck = false;
                }
                bool CheckEmail = false;
                if (dbF.Persons.Find(PerSonId).Email_Address != null)
                {
                    CheckEmail = true;
                }
                else
                {
                    CheckEmail = false;
                }

                if (doc.Bookmarks.Exists("StrAdr") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null && AddressCheck == true)
                {
                    doc.Bookmarks["StrAdr"].Range.Text = GetAdd.GetSpecificAddress(AddressId).Address_Line_1;
                }
                if (doc.Bookmarks.Exists("StrAdr") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null && AddressCheck == false)
                {
                    doc.Bookmarks["StrAdr"].Range.Text = "Not completed";
                }
                if (doc.Bookmarks.Exists("TownAdr") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null && AddressCheck == true)
                {
                    doc.Bookmarks["TownAdr"].Range.Text = dbF.Towns.Find(GetAdd.GetSpecificAddress(AddressId).Town_Id).Description;
                }
                if (doc.Bookmarks.Exists("TownAdr") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null && AddressCheck == false)
                {
                    doc.Bookmarks["TownAdr"].Range.Text = "Not completed";
                }
                if (doc.Bookmarks.Exists("PCodeAdr") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null && AddressCheck == true)
                {
                    doc.Bookmarks["PCodeAdr"].Range.Text = GetAdd.GetSpecificAddress(AddressId).Postal_Code;
                }
                if (doc.Bookmarks.Exists("PCodeAdr") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null && AddressCheck == false)
                {
                    doc.Bookmarks["PCodeAdr"].Range.Text = "Not completed";
                }

                if (doc.Bookmarks.Exists("ContactPerson") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null)
                {
                    doc.Bookmarks["ContactPerson"].Range.Text = dbF.Persons.Find(ParentPersonIdForClientName).First_Name + " " + dbF.Persons.Find(ParentPersonIdForClientName).Last_Name;
                }
                if (doc.Bookmarks.Exists("Date"))
                {
                    doc.Bookmarks["Date"].Range.Text = Convert.ToString(DateTime.Now.ToLongDateString());
                }
                if (doc.Bookmarks.Exists("ClientLetterDate"))
                {
                    doc.Bookmarks["ClientLetterDate"].Range.Text = Convert.ToString(DateTime.Now.ToLongDateString());
                }
                if (doc.Bookmarks.Exists("DateOfReg"))
                {
                    doc.Bookmarks["DateOfReg"].Range.Text = Convert.ToDateTime((from d in dbF.RACAP_Case_Details
                                                                                where d.Intake_Assessment_Id == Assid
                                                                                select d.Date_Registered).FirstOrDefault()).ToString("dd MMMM yyyy");
                }
                if (doc.Bookmarks.Exists("ChildDateOfBirth") && ChildPersonIDForCHildName != 0 && ChildPersonIDForCHildName != null)
                {
                    doc.Bookmarks["ChildDateOfBirth"].Range.Text = Convert.ToString(dbF.Persons.Find(ChildPersonIDForCHildName).Date_Of_Birth);
                }
                if (doc.Bookmarks.Exists("BiologicalMother") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null)
                {
                    doc.Bookmarks["BiologicalMother"].Range.Text = dbF.Persons.Find(ParentPersonIdForClientName).First_Name + " " + dbF.Persons.Find(ParentPersonIdForClientName).Last_Name;
                }
                int MotherClientId = (from m in dbF.Client_Biological_Parents
                                      where m.Person_Id == ParentPersonIdForClientName
                                      select m.Client_Biological_Parent_Id).FirstOrDefault();
                if (doc.Bookmarks.Exists("BiologicalMotherCountry") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null)
                {
                    doc.Bookmarks["BiologicalMotherCountry"].Range.Text = Convert.ToString(dbF.Persons.Find(ParentPersonIdForClientName).Population_Group);
                }
                if (doc.Bookmarks.Exists("BiologicalMotherState") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null)
                {
                    doc.Bookmarks["BiologicalMotherState"].Range.Text = Convert.ToString(dbF.Persons.Find(ParentPersonIdForClientName).Population_Group);
                }
                if (doc.Bookmarks.Exists("BiologicalMotherLanguage") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null)
                {
                    doc.Bookmarks["BiologicalMotherLanguage"].Range.Text = Convert.ToString(dbF.Persons.Find(ParentPersonIdForClientName).Language);
                }
                if (doc.Bookmarks.Exists("AdoptionCity") && AddressCheck == true)
                {
                    doc.Bookmarks["AdoptionCity"].Range.Text = dbF.Towns.Find(GetAdd.GetSpecificAddress(AddressId).Town_Id).Description;
                }
                int?RelId = (from r in dbF.RACAP_Prospective_Parent
                             where r.RACAP_Case_Id == Assid
                             select r.Religion_Id).FirstOrDefault();
                if (doc.Bookmarks.Exists("BiologicalMotherChurch"))
                {
                    if (RelId != null)
                    {
                        doc.Bookmarks["BiologicalMotherChurch"].Range.Text = dbF.Religions.Find(RelId).Description;
                    }
                }
                if (doc.Bookmarks.Exists("BiologicalFather") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null)
                {
                    doc.Bookmarks["BiologicalFather"].Range.Text = dbF.Persons.Find(ParentPersonIdForClientName).First_Name + " " + dbF.Persons.Find(ParentPersonIdForClientName).Last_Name;
                }
                if (doc.Bookmarks.Exists("ChildBirthPlace") && AddressCheck == true)
                {
                    doc.Bookmarks["ChildBirthPlace"].Range.Text = dbF.Towns.Find(GetAdd.GetSpecificAddress(AddressId).Town_Id).Description;
                }
                if (doc.Bookmarks.Exists("ChildNameAtBirth") && ChildPersonIDForCHildName != 0 && ChildPersonIDForCHildName != null)
                {
                    doc.Bookmarks["ChildNameAtBirth"].Range.Text = dbF.Persons.Find(ChildPersonIDForCHildName).First_Name + " " + dbF.Persons.Find(ChildPersonIDForCHildName).Last_Name;
                }
                if (doc.Bookmarks.Exists("SubmissionDate"))
                {
                    doc.Bookmarks["SubmissionDate"].Range.Text = Convert.ToDateTime((from d in dbF.RACAP_Case_Details
                                                                                     where d.Intake_Assessment_Id == Assid
                                                                                     select d.Date_Registered).FirstOrDefault()).ToString("dd MMMM yyyy");
                }
                if (doc.Bookmarks.Exists("PlaceOfExec") && AddressCheck == true)
                {
                    doc.Bookmarks["PlaceOfExec"].Range.Text = dbF.Towns.Find(GetAdd.GetSpecificAddress(AddressId).Town_Id).Description;
                }
                if (doc.Bookmarks.Exists("PlaceOfExec") && AddressCheck == false)
                {
                    doc.Bookmarks["PlaceOfExec"].Range.Text = "Not Completed";
                }
                if (doc.Bookmarks.Exists("Email") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null && CheckEmail == true)
                {
                    doc.Bookmarks["Email"].Range.Text = dbF.Persons.Find(ParentPersonIdForClientName).Email_Address;
                }
                if (doc.Bookmarks.Exists("Email") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null && CheckEmail == false)
                {
                    doc.Bookmarks["Email"].Range.Text = "Not completed";
                }
                if (doc.Bookmarks.Exists("Enquiries"))
                {
                    doc.Bookmarks["Enquiries"].Range.Text = "testc";
                }
                if (doc.Bookmarks.Exists("RefNumber") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null)
                {
                    doc.Bookmarks["RefNumber"].Range.Text = (from r in dbF.Clients
                                                             where r.Person_Id == ParentPersonIdForClientName
                                                             select r.Reference_Number).FirstOrDefault();
                }
                if (doc.Bookmarks.Exists("Telephone") && ParentPersonIdForClientName != 0 && ParentPersonIdForClientName != null)
                {
                    doc.Bookmarks["Telephone"].Range.Text = dbF.Persons.Find(ParentPersonIdForClientName).Phone_Number;
                }
                doc.SaveAs2(savePath);
                app.Application.Quit();

                int Case_Id = (from s in dbF.RACAP_Case_Details
                               where s.Intake_Assessment_Id == Assid
                               select s.RACAP_Case_Id).FirstOrDefault();
                RACAP_Correspondence RCorr = (from c in dbF.RACAP_Correspondence
                                              where c.RACAP_Case_Id == Case_Id && c.RACAP_Correspondence_Type_Id == cases.RACAPCaseViewModel.RACAP_Correspondence_Type_Id
                                              select c).FirstOrDefault();
                if (RCorr != null)
                {
                    RCorr.RACAP_Case_Id = Case_Id;
                    RCorr.RACAP_Correspondence_FileName = Assid + FileName;
                    RCorr.RACAP_Correspondence_FilePath = "~/App_Data/";
                    RCorr.RACAP_Correspondence_Type_Id  = cases.RACAPCaseViewModel.RACAP_Correspondence_Type_Id;
                    RCorr.RACAP_Correspondence_Comments = cases.RACAPCaseViewModel.RACAP_Correspondence_Comments;
                    dbF.SaveChanges();
                }
            }
        }
Example #27
0
        public static void ExportDataToWord(DataGridView DGV, string filename)
        {
            if (DGV.Rows.Count != 0)
            {
                int RowCount    = DGV.Rows.Count;
                int ColumnCount = DGV.Columns.Count;
                Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

                //add rows
                int r = 0;
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    for (r = 0; r <= RowCount - 1; r++)
                    {
                        DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
                    } //end row loop
                }     //end column loop

                Thread.Sleep(10);

                Word.Document oDoc = new Word.Document();

                Thread.Sleep(2000);

                oDoc.Application.Visible = true;

                //page orintation
                oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;

                Thread.Sleep(10);

                dynamic oRange = oDoc.Content.Application.Selection.Range;
                string  oTemp  = "";
                for (r = 0; r <= RowCount; r++)
                {
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        oTemp = oTemp + DataArray[r, c] + "\t";
                    }
                }

                //table format
                oRange.Text = oTemp;
                Thread.Sleep(10);

                object Separator       = Word.WdTableFieldSeparator.wdSeparateByTabs;
                object ApplyBorders    = true;
                object AutoFit         = true;
                object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;
                Thread.Sleep(10);

                oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,
                                      Type.Missing, Type.Missing, ref ApplyBorders,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);
                Thread.Sleep(10);

                oRange.Select();
                Thread.Sleep(2000);

                oDoc.Application.Selection.Tables[1].Select();
                Thread.Sleep(10);
                oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
                Thread.Sleep(10);
                oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
                Thread.Sleep(10);
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                Thread.Sleep(10);
                oDoc.Application.Selection.InsertRowsAbove(1);
                Thread.Sleep(10);
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                Thread.Sleep(10);

                //header row style
                //oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
                //oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma";
                //oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;

                //add header row manually
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
                }
                Thread.Sleep(10);

                oDoc.Application.Selection.Tables[1].Columns[1].Select();
                oDoc.Application.Selection.InsertColumns();
                oDoc.Application.Selection.Tables[1].Columns[1].Select();
                Thread.Sleep(10);

                for (int c = 0; c <= RowCount - 1; c++)
                {
                    oDoc.Application.Selection.Tables[1].Cell(c + 2, 1).Range.Text = DGV.Rows[c].HeaderCell.Value.ToString();
                }
                Thread.Sleep(10);

                //table style
                oDoc.Application.Selection.Tables[1].set_Style("Plain Table 3");
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                Thread.Sleep(10);

                oRange.Select();
                oDoc.Application.Selection.Rows[oDoc.Application.Selection.Rows.Count].Delete();
                oRange.Select();
                oDoc.Application.Selection.Rows[oDoc.Application.Selection.Rows.Count].Delete();

                oRange.Select();
                oDoc.Application.Selection.Tables[1].Columns[1].Width = 25.0f;
                for (int c = 2; c <= ColumnCount + 1; c++)
                {
                    oDoc.Application.Selection.Tables[1].Columns[c].Width = 65;
                }
                //header text
                //foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)
                //{
                //    Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                //    headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
                //    headerRange.Text = "your header text";
                //    headerRange.Font.Size = 16;
                //    headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                //}

                //save the file
                oDoc.SaveAs2(filename);
            }
        }
        public static async Task <List <CockleFilePdf> > CreatePdf(
            IProgress <string> _progress,
            System.Threading.CancellationToken _cancellationToken,
            List <CockleFile> _latestFiles,
            List <CockleFile> _selectedFiles,
            bool _isSingleTicket,
            string _destinationFolderConvertedFiles)
        {
            var pdfCreationModel = new PdfCreationModel(
                _progress,
                _cancellationToken,
                _latestFiles,
                _selectedFiles,
                _isSingleTicket,
                _destinationFolderConvertedFiles);

            bool exceptionThrownInAwait = false; // tracks excptn in await

            List <CockleFile> filesSelectedForConversion;
            bool convertAll = false;

            // get files from grid if null
            if (null == pdfCreationModel.latestFiles)
            {
                filesSelectedForConversion = pdfCreationModel.selectedFiles;
            }
            else
            {
                convertAll = true; filesSelectedForConversion = pdfCreationModel.latestFiles;
            }

            if (filesSelectedForConversion.Count < 1)
            {
                throw new Exception();
            }


            // begin AWAIT
            var filesToReturnFromTask = await System.Threading.Tasks.Task.Run(() =>
            {
                // I think this line can go, as can the OpenMSWordAndCreatePdfs class
                //var files = new OpenMSWordAndCreatePdfs().FilesPrintedSuccessfully;

                //instantiate Word Application & Document
                Word.Application app = new Word.Application();
                app.Visible          = true;
                Word.Document doc    = null;

                //get original printer & prepare to create PDF
                var current_printer   = app.ActivePrinter;
                var adobe_pdf_printer = "Adobe PDF";
                app.ActivePrinter     = adobe_pdf_printer;

                // collection of special class to track files
                var filesPrintedSuccessfully = new List <FilePrintedSuccessfully>();
                //the Word file saved to scratch
                try
                {
                    // counter to track files printed
                    int i = 0;

                    // loop through files
                    foreach (CockleFile fileSelected in filesSelectedForConversion)
                    {
                        // cancel if requested
                        try { pdfCreationModel.cancellationToken.ThrowIfCancellationRequested(); }
                        catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }

                        // catch pdf files saved to Current
                        if (System.IO.Path.GetExtension(fileSelected.FullName).Equals(".pdf"))
                        {
                            // don't try to open, just save to scratch and add to list
                            var pdfFileInCurrent = System.IO.Path.Combine(@"C:\scratch", System.IO.Path.GetFileName(fileSelected.FullName));
                            System.IO.File.Copy(fileSelected.FullName, pdfFileInCurrent);
                            // here, just a string & no cover length
                            filesPrintedSuccessfully.Add(
                                new FilePrintedSuccessfully
                            {
                                CockleFile    = null,
                                TempWordFile  = null,
                                PdfFilename   = pdfFileInCurrent,
                                Filetype      = SourceFileTypeEnum.Camera_Ready, // may have to adjust type here
                                LengthOfCover = null
                            });
                            continue;
                        }

                        // Open docx files in Word, clean up, and convert
                        try
                        {
                            doc = app.Documents.Open(FileName: fileSelected.FullName, ReadOnly: true);
                        }
                        catch
                        {
                            System.Diagnostics.Debug.WriteLine($"{fileSelected.FullName} failed to open");
                        }

                        // save to c:\scratch (overwriting existing files)
                        var tempFileSavedToScratch = System.IO.Path.Combine(@"c:\scratch", System.IO.Path.GetFileName(fileSelected.FullName));
                        if (System.IO.File.Exists(tempFileSavedToScratch))
                        {
                            System.IO.File.Delete(tempFileSavedToScratch);
                        }
                        doc.SaveAs2(FileName: tempFileSavedToScratch);

                        // ctrl shift f9 (had problem with links in index: removes links from main story)
                        Word.Range r = doc.StoryRanges[Word.WdStoryType.wdMainTextStory];
                        r.Fields.Unlink();

                        // delete footer
                        MicrosoftWordStaticClass.WordDoc_DeleteFooters(fileSelected, doc);

                        // line to capture length of cover
                        int?lengthOfCover = null;
                        if (fileSelected.FileType == SourceFileTypeEnum.Cover)
                        {
                            lengthOfCover = MicrosoftWordStaticClass.CaptureCoverLength(doc);
                        }

                        // cancel if requested
                        try { pdfCreationModel.cancellationToken.ThrowIfCancellationRequested(); }
                        catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }

                        // print to pdf, reporting progress
                        var newPdfConvertedFromWord = string.Empty;
                        newPdfConvertedFromWord     = MicrosoftWordStaticClass.PrintToFile(app, doc.FullName);
                        // halt process here: wait for COM background status to end
                        while (app.BackgroundPrintingStatus > 0)
                        {
                            System.Diagnostics.Debug.WriteLine($"app.BackgroundPrintingStatus is {app.BackgroundPrintingStatus}");
                            // cancel if requested
                            try { pdfCreationModel.cancellationToken.ThrowIfCancellationRequested(); }
                            catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }
                        }
                        while (app.BackgroundSavingStatus > 0)
                        {
                            System.Diagnostics.Debug.WriteLine($"app.BackgroundSavingStatus is {app.BackgroundSavingStatus}");
                            // cancel if requested
                            try { pdfCreationModel.cancellationToken.ThrowIfCancellationRequested(); }
                            catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }
                        }

                        // add to files_printed list
                        filesPrintedSuccessfully.Add(
                            new FilePrintedSuccessfully
                        {
                            CockleFile    = fileSelected,
                            TempWordFile  = tempFileSavedToScratch,
                            PdfFilename   = newPdfConvertedFromWord,
                            Filetype      = SourceFileTypeEnum.Unrecognized,
                            LengthOfCover = lengthOfCover
                        });

                        // report to ui

                        // make sure file exists before closing
                        while (!System.IO.File.Exists(newPdfConvertedFromWord))
                        {
                            System.Diagnostics.Debug.WriteLine($"Waiting to print to pdf: {newPdfConvertedFromWord}");
                            // cancel if requested
                            try { pdfCreationModel.cancellationToken.ThrowIfCancellationRequested(); }
                            catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }
                        }
                        // close document & delete temp file
                        doc.Close(SaveChanges: Word.WdSaveOptions.wdDoNotSaveChanges);
                        System.IO.File.Delete(tempFileSavedToScratch);
                        // increment counter
                        i++;
                    }// end for loop to convert each files
                }
                //catch (OperationCanceledException ex) { }
                catch { }
                finally
                {
                    app.ActivePrinter = current_printer;
                    app?.Quit();
                }
                if (exceptionThrownInAwait)
                {
                    // close app
                    app.ActivePrinter = current_printer;
                    app?.Quit();
                    // try to clean folder
                    filesPrintedSuccessfully.ForEach(f =>
                    {
                        if (System.IO.File.Exists(f.PdfFilename))
                        {
                            System.IO.File.Delete(f.PdfFilename);
                        }
                        if (System.IO.File.Exists(f.TempWordFile))
                        {
                            System.IO.File.Delete(f.TempWordFile);
                        }
                    });
                    return(null);
                }

                // block until all files exist
                while (filesPrintedSuccessfully?.Count != filesSelectedForConversion.Count)
                {
                    ;
                }

                #region POINT OF NO RETURN IN CONVERSION
                // convert files to CockleFilePdf
                var cockleFilePdfsPrintedSuccessfully = new List <CockleFilePdf>();
                foreach (var _f in filesPrintedSuccessfully)
                {
                    if (_f.LengthOfCover == null && _f.CockleFile == null)
                    {
                        cockleFilePdfsPrintedSuccessfully.Add(new CockleFilePdf(_f.PdfFilename, _f.Filetype));
                    }
                    else
                    {
                        cockleFilePdfsPrintedSuccessfully.Add(
                            new CockleFilePdf(_f.CockleFile, _f.PdfFilename, _f.LengthOfCover));
                    }
                }

                // test whether all converted files have same ticket
                bool allConvertedFilesSameTicket = cockleFilePdfsPrintedSuccessfully
                                                   .TrueForAll(f => f.TicketNumber ==
                                                               cockleFilePdfsPrintedSuccessfully.First().TicketNumber);

                // move files to unique folder
                if ((allConvertedFilesSameTicket || pdfCreationModel.isSingleTicket) &&
                    cockleFilePdfsPrintedSuccessfully.Count() > 0)    // PROBLEM HERE !!!
                {
                    var firstFile    = cockleFilePdfsPrintedSuccessfully.First();
                    string timeStamp = string.Format("({0} {1}, {2}, {3})", DateTime.Now.ToString("MMM") /*Oct*/,
                                                     DateTime.Now.ToString("dd") /*09*/, DateTime.Now.ToString("yyy") /*2015*/,
                                                     DateTime.Now.ToString("T").ToLower() /*10:58:44 AM*/ /*, len_text*/)
                                       .Replace(':', ' ');
                    var folderName      = $"{firstFile.TicketNumber} {firstFile.Attorney} {timeStamp}";
                    var scratchLocation = @"c:\scratch";

                    var newFolder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(scratchLocation, folderName));

                    foreach (var f in cockleFilePdfsPrintedSuccessfully)
                    {
                        try
                        {
                            var new_filename = System.IO.Path.Combine(newFolder.FullName, f.Filename);
                            System.IO.File.Move(f.FullName, new_filename);

                            // associate new location with CockleFilePdf
                            f.FullName = new_filename;
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex);
                        }
                    }
                }

                // set destination property
                pdfCreationModel.destinationFolderConvertedFiles = System.IO.Path.GetDirectoryName(cockleFilePdfsPrintedSuccessfully.First().FullName);

                // set ranks of pdfs before returning
                pdfCreationModel.setCockleFilePdfRanks(cockleFilePdfsPrintedSuccessfully);

                // combine files into single pdf
                if (convertAll)
                {
                    var createMergedPdfAcrobat = new Models.MergePdf.CreateMergedPDFAcrobat(cockleFilePdfsPrintedSuccessfully);

                    CockleFilePdf mergedCockleFile = null;

                    // add combined file to list of cocklefilepdf files
                    if (System.IO.File.Exists(createMergedPdfAcrobat.CombinedPdfFilename))
                    {
                        mergedCockleFile =
                            new CockleFilePdf(
                                createMergedPdfAcrobat.CombinedPdfFilename,
                                filesSelectedForConversion.First().Attorney,
                                filesSelectedForConversion.First().TicketNumber,
                                SourceFileTypeEnum.Combined_Pdf,
                                "pdf",
                                null);
                        cockleFilePdfsPrintedSuccessfully.Add(mergedCockleFile);
                    }

                    int len_of_cover = -1;
                    if (cockleFilePdfsPrintedSuccessfully.Any(f => f.FileType == SourceFileTypeEnum.Cover))
                    {
                        len_of_cover = cockleFilePdfsPrintedSuccessfully.Where(
                            f => f.FileType == SourceFileTypeEnum.Cover).FirstOrDefault().CoverLength ?? -1;
                    }

                    // remove combined pdf file
                    var cockleFilePdfsPrintedSuccessfullyMinusCombinedFile = cockleFilePdfsPrintedSuccessfully.ToList();
                    cockleFilePdfsPrintedSuccessfullyMinusCombinedFile.Remove(mergedCockleFile);

                    var createImposedPdfiTextSharp =
                        new Models.Imposition.ImposeFullConvertedTicket(
                            pdfCreationModel.destinationFolderConvertedFiles,
                            cockleFilePdfsPrintedSuccessfullyMinusCombinedFile,
                            len_of_cover,
                            TypeOfBindEnum.ProgramDecidesByPageCount);

                    // add imposed files to list of cocklefilepdf files
                    if (createImposedPdfiTextSharp.ImposedFilesCreated.All(f => System.IO.File.Exists(f.FullName)))
                    {
                        createImposedPdfiTextSharp.ImposedFilesCreated.ForEach(f =>
                        {
                            cockleFilePdfsPrintedSuccessfully.Add(
                                new CockleFilePdf(
                                    f.FullName,
                                    filesSelectedForConversion.First().Attorney,
                                    filesSelectedForConversion.First().TicketNumber,
                                    SourceFileTypeEnum.Imposed_Cover_and_Brief,
                                    "pdf",
                                    null));
                        });
                    }
                }
                #endregion


                return(cockleFilePdfsPrintedSuccessfully);
            });

            if (exceptionThrownInAwait)
            {
                throw new OperationCanceledException();
            }
            return(filesToReturnFromTask);
        }
Example #29
0
        private void RaportBtn2_Click(object sender, RoutedEventArgs e)
        {
            if (DGridConsumable.SelectedItem == null)
            {
                return;
            }
            else
            {
                SaveFileDialog openDlg = new SaveFileDialog();
                openDlg.FileName         = "Отчет №";
                openDlg.Filter           = "Word (.doc)|*.doc |Word (.docx)|*.docx |All files (*.*)|*.*";
                openDlg.FilterIndex      = 2;
                openDlg.RestoreDirectory = true;
                if (openDlg.ShowDialog() == true)
                {
                    Word.Application word = new Microsoft.Office.Interop.Word.Application();
                    Word.Document    doc  = word.Documents.Open(Environment.CurrentDirectory + @"\Akt_priyoma_peredachi_materialov.docx");
                    var SelectedInfo      = DGridConsumable.SelectedItems.Cast <ReplenishmentOfMaterials>().FirstOrDefault() as ReplenishmentOfMaterials;
                    var info = AccountingForConsumablesEntities.GetContext().MaterialsInDelivery.Where(w => w.FK_Replenishment == SelectedInfo.id).FirstOrDefault();
                    List <ReplenishmentOfMaterials> materialsInDeliverieLst = new List <ReplenishmentOfMaterials>();
                    materialsInDeliverieLst.AddRange(DGridConsumable.SelectedItems.Cast <ReplenishmentOfMaterials>().ToList());



                    var Worker1 = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 5).FirstOrDefault();
                    var GetDate = DateTime.Today.ToShortDateString();
                    MessageBox.Show("" + materialsInDeliverieLst.Count());
                    try
                    {
                        ReplaceWordStub("{DateOfDelivery}", info.ReplenishmentOfMaterials.DateOfAcceptanceToTheWarehouse.ToShortDateString(), doc);
                        ReplaceWordStub("{DateOfDelivery1}", info.ReplenishmentOfMaterials.DateOfAcceptanceToTheWarehouse.ToShortDateString(), doc);
                        ReplaceWordStub("{ GetDate }", DateTime.Now.ToShortDateString(), doc);
                        ReplaceWordStub("{Position}", AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 5).Select(s => s.Position.PositionName).FirstOrDefault(), doc);
                        ReplaceWordStub("{FirstName}", Worker1.FirstName, doc);
                        ReplaceWordStub("{LastName}", Worker1.LastName, doc);
                        ReplaceWordStub("{MiddleName}", Worker1.MiddleName, doc);
                        ReplaceWordStub("{Manufacturer}", info.MaterialCard.Materials.Manufacturer.ManufacturerName, doc);
                        ReplaceWordStub("{Email}", Worker1.Email, doc);
                        ReplaceWordStub("{ContactPhone}", Worker1.PhoneNumber, doc);
                        int i = 1;
                        foreach (var item in materialsInDeliverieLst)
                        {
                            var newItem = AccountingForConsumablesEntities.GetContext().MaterialsInDelivery.Where(w => w.FK_Replenishment == item.id).FirstOrDefault();

                            ReplaceWordStub("{MaterialGroup" + i + "}", newItem.MaterialCard.Materials.MaterialGroup.NameOfMaterialGroup, doc);
                            ReplaceWordStub("{MaterialName" + i + "}", newItem.MaterialCard.Materials.MaterialName, doc);
                            ReplaceWordStub("{InventNumber" + i + "}", newItem.MaterialCard.InventNumber, doc);
                            ReplaceWordStub("{DeliveryQuantity" + i + "}", newItem.MaterialQuantity.ToString(), doc);
                            i++;
                        }
                        ;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("" + ex);
                    }
                    doc.SaveAs2(openDlg.FileName);
                    doc.Close();
                }
            }
        }
Example #30
0
        private void CreateWordDocument(object filename, object SaveAs)//file name is the temple file y saveAs es el que generamos
        {
            // List<int> processesbeforegen = getRunningProcesses();


            Word.Application wordApp = new Word.Application(); // se crea una word aplication
            object           missing = Missing.Value;          //la función tiene muchos paramtros y no queremos utilizarlos todos

            Word.Document myWordDoc = null;                    //myWordDoc es el documento que vamos a generar y guardar en saveAs file

            if (File.Exists((string)filename))
            {
                object readOnly  = false;//tenemos que escribir en ese documento
                object isVisible = false;
                wordApp.Visible = false;

                myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,//abrimos el machote, ponemos el nombre del maquite que quereos abrir
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing, ref missing);
                myWordDoc.Activate();

                //find and replace
                if (textBox1.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<escrituranumeroradicacion>", textBox1.Text);
                }
                if (textBox2.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<volumenradicacion>", textBox2.Text);
                }
                if (textBox3.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<de cujus>", textBox3.Text);
                }
                if (textBox4.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<albacea>", textBox4.Text);
                }

                if (textBox5.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<testamentonumero>", textBox5.Text);
                }

                if (textBox6.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<testamentovolumen>", textBox6.Text);
                }

                if (textBox7.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<notariotestamento>", textBox7.Text);
                }

                if (textBox8.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<numeronotariotestamento>", textBox8.Text);
                }

                if (textBox9.Text == "")
                {
                }
                else
                {
                    string contenido = textBox9.Text, contenido1 = "", contenido2 = "", contenido3 = "", contenido4 = "", contenido5 = "";
                    string contenido6 = "", contenido7 = "", contenido8 = "", contenido9 = "", contenido10 = "";
                    int    conte = contenido.Length;
                    int    conte1;

                    conte1     = conte / 10;
                    contenido1 = contenido.Substring(0, conte1);//(DE DÓNDE, CUÁNTOS)

                    contenido2 = contenido.Substring(conte1, conte1);

                    contenido3 = contenido.Substring((conte1 + conte1), (conte1));

                    contenido4  = contenido.Substring((3 * conte1), conte1);
                    contenido5  = contenido.Substring((4 * conte1), conte1);
                    contenido6  = contenido.Substring((5 * conte1), conte1);
                    contenido7  = contenido.Substring((6 * conte1), conte1);
                    contenido8  = contenido.Substring((7 * conte1), conte1);
                    contenido9  = contenido.Substring((8 * conte1), conte1);
                    contenido10 = contenido.Substring((9 * conte1), conte1);



                    //this.FindAndReplace(wordApp, "<clausulastestamento>", textBox9.Text);//dynamicTextBox.Text;textBox9.Text
                    this.FindAndReplace(wordApp, "<clausulastestamento1>", contenido1);

                    this.FindAndReplace(wordApp, "<clausulastestamento2>", contenido2);

                    this.FindAndReplace(wordApp, "<clausulastestamento3>", contenido3);

                    this.FindAndReplace(wordApp, "<clausulastestamento4>", contenido4);
                    this.FindAndReplace(wordApp, "<clausulastestamento5>", contenido5);
                    this.FindAndReplace(wordApp, "<clausulastestamento6>", contenido6);
                    this.FindAndReplace(wordApp, "<clausulastestamento7>", contenido7);
                    this.FindAndReplace(wordApp, "<clausulastestamento8>", contenido8);
                    this.FindAndReplace(wordApp, "<clausulastestamento9>", contenido9);
                    this.FindAndReplace(wordApp, "<clausulastestamento10>", contenido10);
                }

                if (textBox10.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<nacionalidad>", textBox10.Text);
                }

                if (textBox11.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<ciudadfallecimiento>", textBox11.Text);
                }

                if (textBox12.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<estadocivilalbacea>", textBox12.Text);
                }

                if (textBox13.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<ocupacionalbacea>", textBox13.Text);
                }

                if (textBox14.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<originarioalbacea>", textBox14.Text);
                }

                if (textBox15.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<domicilioalbacea>", textBox15.Text);
                }

                if (textBox16.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<codigopostalalbacea>", textBox16.Text);
                }

                if (textBox17.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<curpalbacea>", textBox17.Text);
                }

                if (textBox18.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<rfcalbacea>", textBox18.Text);
                }

                if (textBox19.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<inealbacea>", textBox19.Text);
                }


                this.FindAndReplace(wordApp, "<fecha>", dateTimePicker1.Value.ToLongDateString());
                this.FindAndReplace(wordApp, "<fechatestamento>", dateTimePicker2.Value.ToLongDateString());
                this.FindAndReplace(wordApp, "<fechanacimientoalbacea>", dateTimePicker3.Value.ToLongDateString());
                this.FindAndReplace(wordApp, "<fechafallecimiento>", dateTimePicker4.Value.ToLongDateString());
                this.FindAndReplace(wordApp, "<fechacertificadotestamento>", dateTimePicker5.Value.ToLongDateString());

                this.FindAndReplace(wordApp, "<fecha1>", DateTime.Now.ToLongDateString());
            }
            else
            {
                MessageBox.Show("File not Found!");
            }
            //SaveAs2 es el lugar en el que se va a guardar, SaveAs es el camino para generar el documento
            myWordDoc.SaveAs2(ref SaveAs, ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,//
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing);

            myWordDoc.Close(); //esto sí estaba
            wordApp.Quit();    // esto sí estaba
            //MessageBox.Show("File Created!");

            //List<int> processesaftergen = getRunningProcesses();
            //killProcesses(processesbeforegen, processesaftergen);
        }
Example #31
0
        private void doBatch(int pageNum)
        {
            openDoc2(workPath + templateFileName, out templateDocument);


            int firstRow       = (pageNum - 1) * pageRowCount + 1;
            int myDataStartNum = firstRow + dataStartNum - 1;
            int myDataEndNum   = firstRow + dataEndNum - 1;

            string name = ranges.Cells[firstRow + 2, 2].Text;

            if (!(name == "" || name == null))
            {
                if (previousName != name)
                {
                    previousName = name;
                    index++;
                }

                string sex = ranges.Cells[firstRow + 2, 4].Text;
                string birthDateCellValue = ranges.Cells[firstRow + 4, 2].Text;
                string eduCellValue       = ranges.Cells[firstRow + 6, 2].Text;
                string workDateCellValue  = ranges.Cells[firstRow + 2, 8].Text;

                DateTime birthDate = Convert.ToDateTime(birthDateCellValue, dtFormat);

                string edu = "";
                if (!(eduCellValue == "" || eduCellValue == null))
                {
                    //string edu = Regex.Match(eduCellValue, @"\.[0-9][0-9][\S]+?;$").Value;  //正则表达式判断,lazy模式不成功
                    string eduAndDate = eduCellValue.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Last();
                    edu = eduAndDate.Substring(7);
                }

                DateTime workDate = new DateTime();
                if (workDateCellValue.Contains("新参加工作"))
                {
                    string workDateText = workDateCellValue.Substring(0, 7);
                    workDate = Convert.ToDateTime(workDateText, dtFormat);
                }

                WriteLine($"{pageNum}:{firstRow}:{name}:{sex}:{birthDate:yyyy-MM}:{edu}:{workDate:yyyy-MM}");


                #region 填写表格

                for (int i = myDataStartNum; i <= myDataEndNum; i++)
                {
                    string changeReason = ranges.Cells[i, 1].Text;

                    if (changeReason == "聘用岗位")
                    {
                        string executeDate = ranges.Cells[i, 2].Text;

                        string levelCellValue = ranges.Cells[i, 3].Text;
                        string payCellValue   = ranges.Cells[i, 4].Text;

                        foreach (string level in levels)
                        {
                            if (levelCellValue.Contains(level))
                            {
                                levelCellValue = level;
                                break;
                            }
                        }

                        //executeDate.Replace(@".", "-");
                        //executeDate = $"{executeDate}-01";
                        //DateTime executeDateTime = Convert.ToDateTime(executeDate, dtFormat);

                        templateDocument.Variables.Add("姓名", name);
                        templateDocument.Variables.Add("性别", sex);
                        templateDocument.Variables.Add("出生年月", birthDate);
                        templateDocument.Variables.Add("参加工作时间", workDate);
                        templateDocument.Variables.Add("职称", levelCellValue);
                        templateDocument.Variables.Add("聘用时间", executeDate);

                        //更新变量
                        templateDocument.Fields.Update();

                        //删除未填写的变量
                        foreach (Field field in templateDocument.Fields)
                        {
                            field.Select();
                            if (field.Result.Text == "错误!未提供文档变量。")
                            {
                                //WriteLine($"{field.Code.Text}");
                                field.Delete();
                            }
                        }

                        //重新更新变量
                        templateDocument.Fields.Update();


                        templateDocument.SaveAs2($@"{PathHeader}【{index}】【{name}】【{executeDate}】{resultFileNameString}.docx", FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, LockComments: false, CompatibilityMode: 15);
                        #endregion
                    }
                }
            }
        }
Example #32
0
        ///<summary>
        ///Процедура формирования документа
        ///</summary>
        ///<param name="type">Тип документа</param>
        ///<param name="name">Название документа</param>
        ///<param name="table">результирующая таблица</param>
        public void Document_Create(Document_Type type, string name, DataTable table)
        {
            //Получение данных о документе
            Configuration_class configuration_Class = new Configuration_class();

            configuration_Class.Document_Configuration_Get();
            switch (name != "" || name != null)
            {
            case (true):
                switch (type)
                {
                case (Document_Type.Check):
                    //Открытие приложения и документа в нём
                    word.Application application = new word.Application();
                    word.Document    document    = application.Documents.Add(Visible: true);
                    //Формирование документа
                    try
                    {
                        //Начало
                        word.Range range = document.Range(0, 0);
                        //Поля
                        document.Sections.PageSetup.LeftMargin   = application.CentimetersToPoints((float)Configuration_class.doc_Left_Merge);
                        document.Sections.PageSetup.RightMargin  = application.CentimetersToPoints((float)Configuration_class.doc_Right_Merge);
                        document.Sections.PageSetup.TopMargin    = application.CentimetersToPoints((float)Configuration_class.doc_Top_Merge);
                        document.Sections.PageSetup.BottomMargin = application.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge);
                        //Присвоение текстового значения в абзац
                        range.Text = Configuration_class.Organization_Name;
                        //Выравнивание
                        range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        //Интервалы в абзаце
                        range.ParagraphFormat.SpaceAfter      = 1;
                        range.ParagraphFormat.SpaceBefore     = 1;
                        range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle;
                        //Шрифт
                        range.Font.Name = "Times New Roman";
                        range.Font.Size = 12;
                        //Параграф (один Enter)
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        //Название документа
                        word.Paragraph Document_Name = document.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        Document_Name.Range.Font.Name  = "Times New Roman";
                        Document_Name.Range.Font.Size  = 16;
                        Document_Name.Range.Text       = "Выгрузка чека";
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        //Создание таблицы
                        word.Paragraph statparg   = document.Paragraphs.Add();
                        word.Table     stat_table = document.Tables.Add(statparg.Range, table.Rows.Count, table.Columns.Count);
                        //Настройка таблицы
                        stat_table.Borders.InsideLineStyle       = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Borders.OutsideLineStyle      = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Rows.Alignment                = word.WdRowAlignment.wdAlignRowCenter;
                        stat_table.Range.Cells.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        stat_table.Range.Font.Size               = 11;
                        stat_table.Range.Font.Name               = "Times New Roman";
                        //Заполнение таблицы
                        for (int row = 1; row <= table.Rows.Count; row++)
                        {
                            for (int col = 1; col <= table.Columns.Count; col++)
                            {
                                stat_table.Cell(row, col).Range.Text = table.Rows[row - 1][col - 1].ToString();
                            }
                        }
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        //Строка даты создания
                        word.Paragraph Footparg = document.Paragraphs.Add();
                        Footparg.Range.Text = string.Format("Дата создания \t\t\t{0}", DateTime.Now.ToString());
                    }
                    catch
                    {
                    }
                    finally
                    {
                        try
                        {
                            //Сохранение документа
                            document.SaveAs2(name + "DOC", word.WdSaveFormat.wdFormatDocument);
                            //Закрытие документа
                            document.Close(SaveChanges: false);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        application.Quit();
                    }
                    break;

                case (Document_Type.MarkSchemes):
                    //Открытие приложения, создание документа (книги) и листа в нём.
                    excel.Application application_ex = new excel.Application();
                    excel.Workbook    workbook       = application_ex.Workbooks.Add();
                    //excel.Worksheet worksheet = (excel.Worksheet)workbook.ActiveSheet;
                    excel.Worksheet worksheet = workbook.ActiveSheet;
                    try
                    {
                        worksheet.Name        = "MarketerDoc";
                        worksheet.Cells[1][1] = "Отчёт о работе отдела маркетинга";
                        worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count + 1]].Merge();
                        //Заполнение таблицы
                        for (int row = 0; row < table.Rows.Count; row++)
                        {
                            for (int col = 0; col < table.Columns.Count; col++)
                            {
                                worksheet.Cells[row + 3, col + 1] = table.Rows[row][col].ToString();
                            }
                        }
                        //Работа со стилем таблицы
                        excel.Range border1 = worksheet.Range[worksheet.Cells[3, 1], worksheet.Cells[table.Rows.Count + 3][table.Columns.Count]];
                        border1.Borders.LineStyle   = excel.XlLineStyle.xlContinuous;
                        border1.VerticalAlignment   = excel.XlVAlign.xlVAlignCenter;
                        border1.HorizontalAlignment = excel.XlHAlign.xlHAlignCenter;
                        //Дата документа
                        worksheet.Cells[2][table.Rows.Count + 3] = string.Format("Дата создания {0}", DateTime.Now.ToString());
                        //Объединение ячеек
                        worksheet.Range[worksheet.Cells[table.Rows.Count + 3, 2], worksheet.Cells[table.Rows.Count + 3, table.Columns.Count + 2]].Merge();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        //Сохранение и выход
                        workbook.SaveAs(name, application_ex.DefaultSaveFormat);
                        workbook.Close();
                        application_ex.Quit();
                    }
                    break;

                case (Document_Type.Order):
                    //Открытие приложения и документа в нём
                    word.Application application_or = new word.Application();
                    word.Document    document_or    = application_or.Documents.Add(Visible: true);
                    //Формирование документа
                    try
                    {
                        //Начало
                        word.Range range = document_or.Range(0, 0);
                        //Поля
                        document_or.Sections.PageSetup.LeftMargin   = application_or.CentimetersToPoints((float)Configuration_class.doc_Left_Merge);
                        document_or.Sections.PageSetup.RightMargin  = application_or.CentimetersToPoints((float)Configuration_class.doc_Right_Merge);
                        document_or.Sections.PageSetup.TopMargin    = application_or.CentimetersToPoints((float)Configuration_class.doc_Top_Merge);
                        document_or.Sections.PageSetup.BottomMargin = application_or.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge);
                        //Присвоение текстового значения в абзац
                        range.Text = Configuration_class.Organization_Name;
                        //Выравнивание
                        range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        //Интервалы в абзаце
                        range.ParagraphFormat.SpaceAfter      = 1;
                        range.ParagraphFormat.SpaceBefore     = 1;
                        range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle;
                        //Шрифт
                        range.Font.Name = "Times New Roman";
                        range.Font.Size = 12;
                        //Параграф (один Enter)
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        //Название документа
                        word.Paragraph Document_Name = document_or.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        Document_Name.Range.Font.Name  = "Times New Roman";
                        Document_Name.Range.Font.Size  = 16;
                        Document_Name.Range.Text       = table.Rows[0][0].ToString();
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        //Создание таблицы
                        word.Paragraph statparg      = document_or.Paragraphs.Add();
                        word.Paragraph Document_Text = document_or.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Text.Format.Alignment  = word.WdParagraphAlignment.wdAlignParagraphLeft;
                        Document_Text.Format.LeftIndent = (float)1.25;
                        Document_Text.Range.Font.Name   = "Times New Roman";
                        Document_Text.Range.Font.Size   = 14;
                        Document_Text.Range.Text        = table.Rows[0][1].ToString();
                    }
                    catch
                    {
                    }
                    finally
                    {
                        try
                        {
                            //Сохранение документа
                            document_or.SaveAs2(name + "PDF", word.WdSaveFormat.wdFormatPDF);
                            //Закрытие документа
                            document_or.Close(SaveChanges: false);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        application_or.Quit();
                    }
                    break;

                case (Document_Type.Storage):
                    //Открытие приложения и документа в нём
                    word.Application application_St = new word.Application();
                    word.Document    document_St    = application_St.Documents.Add(Visible: true);
                    //Формирование документа
                    try
                    {
                        //Начало
                        word.Range range = document_St.Range(0, 0);
                        //Поля
                        document_St.Sections.PageSetup.LeftMargin   = application_St.CentimetersToPoints((float)Configuration_class.doc_Left_Merge);
                        document_St.Sections.PageSetup.RightMargin  = application_St.CentimetersToPoints((float)Configuration_class.doc_Right_Merge);
                        document_St.Sections.PageSetup.TopMargin    = application_St.CentimetersToPoints((float)Configuration_class.doc_Top_Merge);
                        document_St.Sections.PageSetup.BottomMargin = application_St.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge);
                        //Присвоение текстового значения в абзац
                        range.Text = Configuration_class.Organization_Name;
                        //Выравнивание
                        range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        //Интервалы в абзаце
                        range.ParagraphFormat.SpaceAfter      = 1;
                        range.ParagraphFormat.SpaceBefore     = 1;
                        range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle;
                        //Шрифт
                        range.Font.Name = "Times New Roman";
                        range.Font.Size = 12;
                        //Параграф (один Enter)
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        //Название документа
                        word.Paragraph Document_Name = document_St.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        Document_Name.Range.Font.Name  = "Times New Roman";
                        Document_Name.Range.Font.Size  = 16;
                        Document_Name.Range.Text       = "Выгрузка чека";
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        //Создание таблицы
                        word.Paragraph statparg   = document_St.Paragraphs.Add();
                        word.Table     stat_table = document_St.Tables.Add(statparg.Range, table.Rows.Count, table.Columns.Count);
                        //Настройка таблицы
                        stat_table.Borders.InsideLineStyle       = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Borders.OutsideLineStyle      = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Rows.Alignment                = word.WdRowAlignment.wdAlignRowCenter;
                        stat_table.Range.Cells.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        stat_table.Range.Font.Size               = 11;
                        stat_table.Range.Font.Name               = "Times New Roman";
                        //Заполнение таблицы
                        for (int row = 1; row <= table.Rows.Count; row++)
                        {
                            for (int col = 1; col <= table.Columns.Count; col++)
                            {
                                stat_table.Cell(row, col).Range.Text = table.Rows[row - 1][col - 1].ToString();
                            }
                        }
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        //Строка даты создания
                        word.Paragraph Footparg = document_St.Paragraphs.Add();
                        Footparg.Range.Text = string.Format("Дата создания \t\t\t{0}", DateTime.Now.ToString());
                    }
                    catch
                    {
                    }
                    finally
                    {
                        try
                        {
                            //Сохранение документа
                            document_St.SaveAs2(name + "DOC", word.WdSaveFormat.wdFormatDocument);
                            //Закрытие документа
                            document_St.Close(SaveChanges: false);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        application_St.Quit();
                    }
                    break;
                }
                break;

            case (false):
                MessageBox.Show("Введите название документа");
                break;
            }
        }
Example #33
0
        private void CreateDocument()
        {
            DataGridView secim = null;

            try
            {
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
                winword.ShowAnimation = false;
                winword.Visible       = false;
                object missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                document.Content.SetRange(0, 0);
                document.Content.Text = "Print Document" + Environment.NewLine;

                Paragraph para = document.Content.Paragraphs.Add(ref missing);
                para.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                if (gsm.SelectedIndex == 1)
                {
                    secim           = AboneView;
                    para.Range.Text = "Abone Tablosu" + Environment.NewLine;
                }
                else if (gsm.SelectedIndex == 2)
                {
                    secim           = TarifeView;
                    para.Range.Text = "Tarife Tablosu" + Environment.NewLine;
                }
                else if (gsm.SelectedIndex == 3)
                {
                    secim           = HatView;
                    para.Range.Text = "Hat Tablosu" + Environment.NewLine;
                }
                else if (gsm.SelectedIndex == 4)
                {
                    secim           = FaturaView;
                    para.Range.Text = "Fatura Tablosu" + Environment.NewLine;
                }
                para.Range.InsertParagraphAfter();

                Table firstTable = document.Tables.Add(para.Range, secim.RowCount, secim.ColumnCount, ref missing, ref missing);

                foreach (Row row in firstTable.Rows)
                {
                    foreach (Cell cell in row.Cells)
                    {
                        cell.Range.Text = secim.Rows[cell.RowIndex - 1].Cells[cell.ColumnIndex - 1].Value.ToString();
                    }
                }
                firstTable.Borders.Enable = 1;
                string         savePath = "";
                SaveFileDialog sf       = new SaveFileDialog();


                if (sf.ShowDialog() == DialogResult.OK)
                {
                    savePath = sf.FileName;
                }
                object filename = savePath + ".doc";
                document.SaveAs2(ref filename);
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;
                MessageBox.Show("Document created successfully !");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void sendIt_Click(object sender, RoutedEventArgs e)
        {
            File.Copy(@"C:\Users\Public\ReportManager\templateBackup.docx", @"C:\Users\Public\ReportManager\template.docx", true);
            int    totalMaquinado = 0, totalOficina = 0, totalSoldadura = 0, totalAlmacen = 0, total = 0, alm = 0, maq = 0, of = 0, sold = 0, completed = 0, pending = 0, waiting = 0, verify = 0, inStock = 0;
            string trackID = "", requestName = "OA -WAS-" + DateTime.Today.Month + "-" + DateTime.Today.Year;
            string connectionString = "server=localhost; database=receiptManagerDB; user=root; password=; Allow Zero Datetime=True; Convert Zero Datetime=True";

            if (requestList.Items.Count > 0)
            {
                DateTime init = DateTime.Today, end = DateTime.Today;
                for (int i = 0; i < requestList.Items.Count; i++)
                {
                    data dataObject = (data)requestList.Items[i];
                    DateTime.TryParse(dataObject.realDeliverDate.ToString(), out end);
                    trackID = dataObject.trackID;
                    if (end < init)
                    {
                        init = end;
                    }
                    switch (dataObject.department)
                    {
                    case "Maquinados":
                        totalMaquinado += int.Parse(dataObject.spentMoney);
                        maq            += 1;
                        break;

                    case "Oficina":
                        totalOficina += int.Parse(dataObject.spentMoney);
                        of           += 1;
                        break;

                    case "Soldadura":
                        totalSoldadura += int.Parse(dataObject.spentMoney);
                        sold           += 1;
                        break;

                    case "Almacen":
                        totalAlmacen += int.Parse(dataObject.spentMoney);
                        alm          += 1;
                        break;
                    }
                    switch (dataObject.status)
                    {
                    case "Completada":
                        completed += 1;
                        break;

                    case "Pendiente Importar":
                        pending += 1;
                        break;

                    case "En espera de llegada":
                        waiting += 1;
                        break;

                    case "Verificar Informacion":
                        verify += 1;
                        break;

                    case "En planta":
                        inStock += 1;
                        break;
                    }
                    MySqlCommand    cmd;
                    MySqlDataReader reader;
                    using (MySqlConnection conn = new MySqlConnection(connectionString))
                    {
                        try
                        {
                            conn.Open();
                            cmd             = conn.CreateCommand();
                            cmd.CommandText = "UPDATE `requests` SET `status`='Completada' WHERE `requestOrder`='" + dataObject.requestID + "';";
                            //UPDATE `requestsinfo` SET `status`='something' WHERE id
                            reader = cmd.ExecuteReader();
                            conn.Close();
                        }
                        catch (MySqlException ex)
                        {
                            MessageBox.Show("Conection error with the DB " + ex.Message.ToString(), "Warning", MessageBoxButton.OK);
                        }
                    }
                }
                total = totalMaquinado + totalOficina + totalSoldadura + totalAlmacen;
                Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    wordDoc = wordApp.Documents.Open(@"C:\Users\Public\ReportManager\template.docx", Visible: false);
                string   classtype = "Excel.Chart.8";
                Bookmark bkm       = wordDoc.Bookmarks["trackID"];
                Microsoft.Office.Interop.Word.Range rng = bkm.Range;
                rng.Text = trackID;
                bkm      = wordDoc.Bookmarks["managerName"];
                rng      = bkm.Range;
                rng.Text = name;
                bkm      = wordDoc.Bookmarks["requestOrder"];
                rng      = bkm.Range;
                rng.Text = requestName;
                bkm      = wordDoc.Bookmarks["initDate"];
                rng      = bkm.Range;
                rng.Text = init.Date.Day + "/" + init.Date.Month + "/" + init.Date.Year;
                bkm      = wordDoc.Bookmarks["endDate"];
                rng      = bkm.Range;
                rng.Text = end.Date.Day + "/" + end.Date.Month + "/" + end.Date.Year;
                bkm      = wordDoc.Bookmarks["creationDate"];
                rng      = bkm.Range;
                rng.Text = DateTime.Today.Day + "/" + DateTime.Today.Month + "/" + DateTime.Today.Year;
                //////CHARTS PIE
                bkm = wordDoc.Bookmarks.get_Item("pieChart");
                Microsoft.Office.Interop.Word.InlineShape wrdInlineShape = wordDoc.InlineShapes.AddOLEObject(classtype);
                object oEndOfDoc = "pieChart";
                if (wrdInlineShape.OLEFormat.ProgID == "Excel.Chart.8")
                {
                    object verb = Microsoft.Office.Interop.Word.WdOLEVerb.wdOLEVerbHide;
                    wrdInlineShape.OLEFormat.DoVerb(ref verb);
                    Microsoft.Office.Interop.Excel.Workbook  obook = (Microsoft.Office.Interop.Excel.Workbook)wrdInlineShape.OLEFormat.Object;
                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)obook.Worksheets["Sheet1"];

                    obook.Application.Visible = false;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 1]).Value = "Departamentos";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 1]).Value = "Almacen";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 1]).Value = "Maquinado";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 1]).Value = "Oficinas";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 1]).Value = "Soldadura";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 1]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 1]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 2]).Value = "Costos";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 2]).Value = totalAlmacen;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 2]).Value = totalMaquinado;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 2]).Value = totalOficina;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 2]).Value = totalSoldadura;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 2]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 2]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 3]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 4]).ClearContents();

                    wrdInlineShape.Width = 400;

                    obook.ActiveChart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xl3DPie;
                    Microsoft.Office.Interop.Word.Range wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    object oRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    sheet.UsedRange.Copy();
                    wordDoc.SetDefaultTableStyle("Light List - Accent 4", false);
                    wrdRng.PasteExcelTable(true, true, false);
                    wrdInlineShape.ConvertToShape();
                    obook.Close();
                }
                //baaars chart
                bkm            = wordDoc.Bookmarks.get_Item("barChart");
                wrdInlineShape = wordDoc.InlineShapes.AddOLEObject(classtype);
                oEndOfDoc      = "barChart";
                if (wrdInlineShape.OLEFormat.ProgID == "Excel.Chart.8")
                {
                    object verb = Microsoft.Office.Interop.Word.WdOLEVerb.wdOLEVerbHide;
                    wrdInlineShape.OLEFormat.DoVerb(ref verb);
                    Random rn = new Random();
                    Microsoft.Office.Interop.Excel.Workbook  obook = (Microsoft.Office.Interop.Excel.Workbook)wrdInlineShape.OLEFormat.Object;
                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)obook.Worksheets["Sheet1"];

                    obook.Application.Visible = false;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 1]).Value = "Departamentos";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 1]).Value = "Almacen";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 1]).Value = "Maquinado";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 1]).Value = "Oficinas";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 1]).Value = "Soldadura";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 1]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 1]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 2]).Value = "Total de requerimientos";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 2]).Value = alm;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 2]).Value = maq;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 2]).Value = of;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 2]).Value = sold;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 2]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 2]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 3]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 4]).ClearContents();
                    wrdInlineShape.Width = 400;

                    obook.ActiveChart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xl3DLine;
                    Microsoft.Office.Interop.Word.Range wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    object oRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    sheet.UsedRange.Copy();
                    wordDoc.SetDefaultTableStyle("Light List - Accent 4", false);
                    wrdRng.PasteExcelTable(true, true, false);
                    wrdInlineShape.ConvertToShape();
                    obook.Close();
                }
                //Lines chart
                bkm            = wordDoc.Bookmarks.get_Item("linesChart");
                wrdInlineShape = wordDoc.InlineShapes.AddOLEObject(classtype);
                oEndOfDoc      = "linesChart";
                if (wrdInlineShape.OLEFormat.ProgID == "Excel.Chart.8")
                {
                    object verb = Microsoft.Office.Interop.Word.WdOLEVerb.wdOLEVerbHide;
                    wrdInlineShape.OLEFormat.DoVerb(ref verb);
                    Microsoft.Office.Interop.Excel.Workbook  obook = (Microsoft.Office.Interop.Excel.Workbook)wrdInlineShape.OLEFormat.Object;
                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)obook.Worksheets["Sheet1"];

                    obook.Application.Visible = false;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 1]).Value = "Estatus";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 1]).Value = "Completada";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 1]).Value = "Pendiente Importar";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 1]).Value = "En espera de llegada";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 1]).Value = "Verificar Informacion";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 1]).Value = "En planta";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 1]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 2]).Value = "Cantidad de requerimientos";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 2]).Value = completed;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 2]).Value = pending;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 2]).Value = waiting;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 2]).Value = verify;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 2]).Value = inStock;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 2]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 3]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 4]).ClearContents();

                    wrdInlineShape.Width = 400;

                    obook.ActiveChart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xl3DBarStacked;
                    Microsoft.Office.Interop.Word.Range wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    object oRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    sheet.UsedRange.Copy();
                    wordDoc.SetDefaultTableStyle("Light List - Accent 4", false);
                    wrdRng.PasteExcelTable(true, true, false);
                    wrdInlineShape.ConvertToShape();
                    obook.Close();
                }
                object fileName = @"C:\Users\Public\ReportManager\Reportes\Request_Report #" + requestName + ".docx";
                try
                {
                    wordDoc.SaveAs2(fileName);
                    MessageBox.Show("Se creó el archivo satisfactoriamente", "¡Listo!", MessageBoxButton.OK);
                }
                catch (Exception exc)
                {
                    MessageBox.Show("Hubo un error con el archivo" + exc.Message.ToString(), "¡ERROR!", MessageBoxButton.OK);
                }
                wordDoc.Close();
                wordApp.Quit();
                Process.Start(fileName.ToString());
                Process.Start(@"C:\Users\Public\ReportManager\Reportes\");
                MainWindow main = new MainWindow();
                main.Show();
                Close();
            }
        }
Example #35
0
        private void CreateDocument()
        {
            try
            {
                //Create an instance for word app
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

                //Set animation status for word application
                winword.ShowAnimation = false;

                //Set status for word application is to be visible or not.
                winword.Visible = false;

                //Create a missing variable for missing value
                object missing = System.Reflection.Missing.Value;

                //Create a new document
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                //Add header into the document
                foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
                {
                    //Get the header range and add the header details.
                    Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                    headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    headerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
                    headerRange.Font.Size = 10;
                    headerRange.Text      = txtTitle.Text;//"Header text goes here";
                }

                /*
                 * //Add the footers into the document
                 * foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                 * {
                 *  //Get the footer range and add the footer details.
                 *  Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                 *  footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
                 *  footerRange.Font.Size = 10;
                 *  footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                 *  footerRange.Text = "Footer text goes here";
                 * }
                 * */

                /*
                 * //adding text to document
                 * document.Content.SetRange(0, 0);
                 * document.Content.Text = "This is test document " + Environment.NewLine;
                 *
                 * //Add paragraph with Heading 1 style
                 * Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
                 * object styleHeading1 = "Heading 1";
                 * para1.Range.set_Style(ref styleHeading1);
                 * para1.Range.Text = "Para 1 text";
                 * para1.Range.InsertParagraphAfter();
                 *
                 * //Add paragraph with Heading 2 style
                 * Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
                 * object styleHeading2 = "Heading 2";
                 * para2.Range.set_Style(ref styleHeading2);
                 * para2.Range.Text = "Para 2 text";
                 * para2.Range.InsertParagraphAfter();
                 * */

                //them, neu lay o tren thi bo cai nay
                Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);

                //Create a 5X5 table and insert some dummy record
                Table firstTable = document.Tables.Add(para1.Range, 2, 2, ref missing, ref missing);

                firstTable.Borders.Enable = 1;
                foreach (Row row in firstTable.Rows)
                {
                    foreach (Cell cell in row.Cells)
                    {
                        //Header row
                        if (cell.RowIndex == 1)
                        {
                            if (cell.ColumnIndex == 1)
                            {
                                cell.Range.Text = "Engsub";//"Column " + cell.ColumnIndex.ToString();
                            }
                            else
                            {
                                cell.Range.Text = "Vietsub";
                            }
                            cell.Range.Font.Bold = 1;
                            //other format properties goes here
                            cell.Range.Font.Name = "verdana";
                            cell.Range.Font.Size = 10;
                            //cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;
                            cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                            //Center alignment for the Header cells
                            cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                        }
                        //Data row
                        else
                        {
                            if (cell.ColumnIndex == 1)
                            {
                                cell.Range.Text = txtEngsub.Text;
                            }
                            else
                            {
                                cell.Range.Text = txtVietsub.Text;
                            }
                            //cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
                        }
                    }
                }

                //Save the document
                object filename = @"E:\english\Friends\Friends Season 1 COMPLETE 720p.BRrip.sujaidr (pimprg)\" + txtTitle.Text + ".docx";//"E:\Friends\documents\"+ txtTitle.Text +".docx";
                document.SaveAs2(ref filename);
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;
                MessageBox.Show("Document created successfully !");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #36
0
        public void AddHeaderAndFooterToDocFile()
        {
            try
            {
                //Gets Gnh Utility Process Path
                string gnhAppPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                string rawReportDirectory       = gnhAppPath + @"\Raw\";
                string processedReportDirectory = gnhAppPath + @"\Processed\";

                if (!System.IO.Directory.Exists(rawReportDirectory))
                {
                    System.IO.Directory.CreateDirectory(rawReportDirectory);
                }

                if (!System.IO.Directory.Exists(processedReportDirectory))
                {
                    System.IO.Directory.CreateDirectory(processedReportDirectory);
                }

                object oTrue    = true;
                object oFalse   = false;
                object oMissing = System.Reflection.Missing.Value;
                object novalue  = System.Reflection.Missing.Value;
                object missing  = System.Reflection.Missing.Value;
                object gnhHeaderFooterTemplate = gnhAppPath + @"\Template\GNH_Template.doc";
                //object fileName2 = @"C:\Users\ckakdep\Desktop\Interpidians\POC\Subhash\Project\Project\Diet_20170215\Diet\GeetaNeutriHealUtility\Report\Alka_15Feb2017.doc";
                object newTemplate = false;
                object docType     = 0;
                object isVisible   = true;
                Microsoft.Office.Interop.Word.ApplicationClass questionClient = new Microsoft.Office.Interop.Word.ApplicationClass();


                Microsoft.Office.Interop.Word.Document questionDoc1 = questionClient.Documents.Open(ref gnhHeaderFooterTemplate, ref newTemplate, ref docType, ref isVisible);
                questionDoc1.Activate();

                Console.WriteLine("Report Processing Started");

                foreach (var fileName in System.IO.Directory.GetFiles(rawReportDirectory, "*.doc"))
                {
                    Object fileName2 = fileName;
                    Microsoft.Office.Interop.Word.Document questionDoc2 = questionClient.Documents.Open(ref fileName2, ref newTemplate, ref docType, ref isVisible);
                    questionDoc2.Activate();

                    questionDoc1.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.CopyAsPicture();
                    questionDoc2.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Paste();
                    questionDoc1.Sections[1].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.CopyAsPicture();
                    questionDoc2.Sections[1].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Paste();

                    //saving the document
                    questionDoc2.SaveAs2(fileName2.ToString().Replace("Raw", "Processed"), Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument);
                    questionDoc2.Close(true, oMissing, oMissing);

                    //icrement the processed file count
                    noOfFilesProcessed++;
                }

                //questionDoc2.Save(); // Don't use this to save as it create extra folders while saving word file

                //closing the document
                questionClient.Documents.Save(ref oMissing, ref oMissing);

                //closing word instance
                questionClient.Quit(ref oMissing, ref oMissing, ref oMissing);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured during processing");
                Console.WriteLine("Kill the winword.exe process from task manager and try again or call administrator for assistance");
            }
        }
Example #37
0
        private void GenerateMemberReport()
        {
            var WeekMembers = GetAPPeriodMembers();

            foreach (var thisMember in WeekMembers)
            {
                var FileName = "MEMBERREPORT(" + thisMember.MemberID + ")-"
                               + dbs.ap_period.Where(m => m.EndDate <= today).Max(m => m.APPeriodID)
                               + ".docx";

                //Create a new document
                Microsoft.Office.Interop.Word.Application winword  = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    document = winword.Documents.Add();

                //Add header into the document
                foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
                {
                    Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                    headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    headerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlack;
                    headerRange.Font.Size = 20;
                    headerRange.Text      = "Weekly Billing Report";
                }

                document.Content.SetRange(0, 0);
                var buildString = new StringBuilder();

                buildString.AppendLine("AP Period: " + lastWeek.ToShortDateString() +
                                       " - " + today.ToShortDateString());

                buildString.AppendLine();
                buildString.AppendLine(thisMember.FirstName + " " + thisMember.LastName);
                buildString.AppendLine(thisMember.Phone);
                buildString.AppendLine(thisMember.Email);
                buildString.AppendLine(thisMember.Address);
                buildString.AppendLine(thisMember.City + ", " + thisMember.State + " " + thisMember.Zip);
                buildString.AppendLine();

                var billings = GetAPPeriodBill_infoByMember(thisMember);

                document.Content.Text = buildString.ToString();

                Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add();

                para1.Range.InsertParagraphAfter();
                Table firstTable = document.Tables.Add(para1.Range, billings.Count + 1, 3);
                firstTable.Borders.Enable = 1;

                foreach (Row row in firstTable.Rows)
                {
                    foreach (Cell cell in row.Cells)
                    {
                        //Header row
                        if (cell.RowIndex == 1)
                        {
                            if (cell.ColumnIndex == 1)
                            {
                                cell.Range.Text = "Date of Service";
                            }
                            else if (cell.ColumnIndex == 2)
                            {
                                cell.Range.Text = "Provider Name";
                            }
                            else
                            {
                                cell.Range.Text = "Service Name";
                            }
                        }
                        else
                        {
                            var thisBilling = billings[cell.RowIndex - 2];

                            if (cell.ColumnIndex == 1)
                            {
                                cell.Range.Text = thisBilling.ServiceDate.Value.ToShortDateString();
                            }
                            else if (cell.ColumnIndex == 2)
                            {
                                cell.Range.Text = thisBilling.provider.FirstName + " " + thisBilling.provider.LastName;
                            }
                            else
                            {
                                cell.Range.Text = thisBilling.service?.ServiceName ?? "";
                            }
                        }
                    }
                }

                //Add the footers into the document
                foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                {
                    //Get the footer range and add the footer details.
                    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlack;
                    footerRange.Font.Size                 = 10;
                    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                    footerRange.Text = FileName;
                }

                //Save the document
                object filename = FileName;
                document.SaveAs2(ref filename);
                document.Close();
                document = null;
                winword.Quit();
                winword = null;
            }
        }
Example #38
0
        private void doBatch(int rowNum)
        {
            openDoc2(workPath + templateFileName, out templateDocument);

            Dictionary <string, string> dict = new Dictionary <string, string>();

            for (int j = 1; j <= keyNum; j++)
            {
                string dictKey   = ranges.Cells[2, j].Text;
                string dictValue = ranges.Cells[rowNum, j].Text;
                WriteLine($"dictKey:{dictKey}, dictValue:{dictValue}");
                dict.Add(dictKey, dictValue);
            }

            if (!(dict["id"] == "" || dict["id"] == null))
            {
                /*
                 * string PathHeader = $@"{workPath}{dict["Name"]}({dict["Class"]})\";
                 * WriteLine(PathHeader);
                 *
                 * if (!Directory.Exists(PathHeader))
                 * {
                 *  Directory.CreateDirectory(PathHeader);
                 *
                 * }
                 */

                #region 填写表格

                foreach (string key in dict.Keys)
                {
                    /*
                     * 不填写以下数据:
                     * class_zj;class_gq, 根据情况打钩或不打钩
                     */
                    if (key == "class_zj" || key == "class_gq")
                    {
                        //Pass
                    }
                    else
                    {
                        templateDocument.Variables.Add(key, dict[key]);
                    }
                }

                if (dict["class"] == "专技")
                {
                    templateDocument.Variables.Add("class_zj", "☑");
                    templateDocument.Variables.Add("class_gq", "□");
                }
                else if (dict["class"] == "工勤")
                {
                    templateDocument.Variables.Add("class_gq", "☑");
                    templateDocument.Variables.Add("class_zj", "□");
                }


                //更新变量
                templateDocument.Fields.Update();

                //删除未填写的变量
                foreach (Field field in templateDocument.Fields)
                {
                    field.Select();
                    if (field.Result.Text == "错误!未提供文档变量。")
                    {
                        //WriteLine($"{field.Code.Text}");
                        field.Delete();
                    }
                }

                //重新更新变量
                templateDocument.Fields.Update();


                #endregion

                templateDocument.SaveAs2($@"{PathHeader}【{dict["id"]}】【{dict["name"]}】招聘登记表.docx", FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, LockComments: false, CompatibilityMode: 15);

                templateDocument.Close(SaveChanges: false);
            }
        }
Example #39
0
        private Document creatAOI()
        {
            if (!rncaao.Keys.Contains("图纸名称"))
            {
                rncaao.Add("图纸名称", AutorivetDB.queryno(rncaao["图号"], "图纸名称"));
            }



            wordApp         = new Microsoft.Office.Interop.Word.Application();
            wordApp.Visible = true;
            myAO            = new Document();
            if (File.Exists(rncaao["AOI保存地址"]) && (!checkBox1.Checked))
            {
                myAO = wordApp.Documents.Open(rncaao["AOI保存地址"]);
            }
            else
            {
                if (rncaao["中文名称"].Contains("CS300"))
                {
                    myAO = wordApp.Documents.Open(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "wordModel\\AOI\\AOI_CS300.docx");
                }
                else
                {
                    myAO = wordApp.Documents.Open(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "wordModel\\AOI\\AOI.docx");
                }



                myAO.SaveAs2(rncaao["AOI保存地址"]);
            }



            myAO.Tables[1].Cell(3, 2).Range.Text = rncaao["AOI编号"];

            //替换所有编号
            wordMethod.SearchReplace(wordApp, myAO, "C1-CF510-010", rncaao["AOI编号"]);



            //标题


            myAO.Tables[1].Cell(3, 4).Range.Text = rncaao["中文名称"] + "壁板自动钻铆\rAUTO-RIVETING OF " + rncaao["图纸名称"];

            //装配图号
            myAO.Tables[1].Cell(4, 2).Range.Text = rncaao["装配图号"];
            //替换所有装配图号

            wordMethod.SearchReplace(wordApp, myAO, "C02311100", rncaao["装配图号"]);



            //进入零件表填写


            //第一条


            myAO.Tables[2].Cell(3, 1).Range.Text = "1";
            //     myAO.Tables[2].Cell(3, 1).Height=
            myAO.Tables[2].Cell(3, 2).Range.Text = rncaao["图号"] + "P1";
            myAO.Tables[2].Cell(3, 3).Range.Text = rncaao["中文名称"] + "壁板组件\r" + rncaao["图纸名称"];
            myAO.Tables[2].Cell(3, 4).Range.Text = "A";
            myAO.Tables[2].Cell(3, 5).Range.Text = "1";
            myAO.Tables[2].Cell(3, 6).Range.Text = rncaao["装配图号"];

            // myAO.Tables[1].Cell(7, 10).Range.Text = rncaao["架次"];
            // myAO.Tables[1].Cell(7, 1).Range.Text = dataGridView1.Rows[0].

            //开始统计紧固件

            System.Data.DataTable fsttable = AutorivetDB.spfsttable(rncaao["图号"]);

            int fstcount = fsttable.Rows.Count;
            int nut5     = 0;
            int nut6     = 0;

            if (fstcount != 0)
            {
                for (int i = 0; i < fstcount; i++)
                {
                    string fstno = fsttable.Rows[i][0].ToString();
                    myAO.Tables[2].Cell(4 + i, 1).Range.Text = (i + 2).ToString();
                    myAO.Tables[2].Cell(4 + i, 2).Range.Text = fstno;
                    //string fstname = "";


                    if (fstno.Contains("B020600"))
                    {
                        myAO.Tables[2].Cell(4 + i, 3).Range.Text = "高锁\rHI-LITE";
                        int hiqty = System.Convert.ToInt16(fsttable.Rows[i][1].ToString());

                        if (fstno.Contains("AG5"))
                        {
                            nut5 = nut5 + hiqty;
                        }
                        else
                        {
                            nut6 = nut6 + hiqty;
                        }
                    }
                    else
                    {
                        myAO.Tables[2].Cell(4 + i, 3).Range.Text = "铆钉\rRIVET";
                    }
                    myAO.Tables[2].Cell(4 + i, 4).Range.Text = "U";
                    myAO.Tables[2].Cell(4 + i, 5).Range.Text = fsttable.Rows[i][1].ToString();
                    myAO.Tables[2].Cell(4 + i, 6).Range.Text = rncaao["装配图号"];
                }



                fstcount = 4 + fstcount;
                if (nut5 != 0)
                {
                    myAO.Tables[2].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                    myAO.Tables[2].Cell(fstcount, 2).Range.Text = "B0203013-08";
                    myAO.Tables[2].Cell(fstcount, 3).Range.Text = "高锁帽\rNUT";
                    myAO.Tables[2].Cell(fstcount, 4).Range.Text = "U";
                    myAO.Tables[2].Cell(fstcount, 5).Range.Text = nut5.ToString();
                    myAO.Tables[2].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];
                    if (nut6 != 0)
                    {
                        fstcount = fstcount + 1;
                        myAO.Tables[2].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                        myAO.Tables[2].Cell(fstcount, 2).Range.Text = "B0203013-3";
                        myAO.Tables[2].Cell(fstcount, 3).Range.Text = "高锁帽\rNUT";
                        myAO.Tables[2].Cell(fstcount, 4).Range.Text = "U";
                        myAO.Tables[2].Cell(fstcount, 5).Range.Text = nut6.ToString();
                        myAO.Tables[2].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];
                    }
                }
                else
                {
                    if (nut6 != 0)
                    {
                        //fstcount = fstcount + 1;
                        myAO.Tables[2].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                        myAO.Tables[2].Cell(fstcount, 2).Range.Text = "B0203013-3";
                        myAO.Tables[2].Cell(fstcount, 3).Range.Text = "高锁帽\rNUT";
                        myAO.Tables[2].Cell(fstcount, 4).Range.Text = "U";
                        myAO.Tables[2].Cell(fstcount, 5).Range.Text = nut6.ToString();
                        myAO.Tables[2].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];
                    }
                }
                //添加密封胶
                if ((nut5 + nut6) == 0)
                {
                }
                else
                {
                    fstcount = fstcount + 1;
                }

                myAO.Tables[2].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                myAO.Tables[2].Cell(fstcount, 3).Range.Text = "密封剂\rSEALANT";
                myAO.Tables[2].Cell(fstcount, 2).Range.Text = "MIL-PRF-81733 Type IV";
                myAO.Tables[2].Cell(fstcount, 4).Range.Text = "M";
                myAO.Tables[2].Cell(fstcount, 5).Range.Text = "340g";
                myAO.Tables[2].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];

                //添加胶嘴
                //fstcount = fstcount + 1;
                //List<string> tipls = autorivet_op.processitemlist(rncaao["装配图号"], "胶嘴Sealant_Tip");
                //for (int k=0;k<tipls.Count();k++)
                //{

                //    myAO.Tables[2].Cell(fstcount+k, 1).Range.Text = (fstcount+k - 2).ToString();
                //    myAO.Tables[2].Cell(fstcount + k, 2).Range.Text = tipls[k];
                //    myAO.Tables[2].Cell(fstcount + k, 3).Range.Text = "胶嘴\rSealant Tip";
                //    myAO.Tables[2].Cell(fstcount + k, 4).Range.Text = "M";
                //    myAO.Tables[2].Cell(fstcount + k, 5).Range.Text = "1";
                //    myAO.Tables[2].Cell(fstcount + k, 6).Range.Text = rncaao["装配图号"];

                //}

                //添加下铆头

                fstcount = fstcount + 1;


                while (!myAO.Tables[2].Cell(fstcount, 1).Range.Text.Contains("专用工具"))
                {
                    fstcount = fstcount + 1;
                }

                //定位到要输入专用工具的行
                fstcount = fstcount + 2;



                List <string> lals = AutorivetDB.processitemlist(rncaao["装配图号"], "下铆头Lower_Anvil");
                //最多只能放下三行
                //用于记录行尾,指示下一行数据的索引;
                int rear = fstcount;

                for (int k = 0; k < lals.Count(); k++)
                {
                    myAO.Tables[2].Cell(rear, 1).Range.Text = (k + 1).ToString();
                    myAO.Tables[2].Cell(rear, 2).Range.Text = "下铆头\rLower Anvil";
                    myAO.Tables[2].Cell(rear, 3).Range.Text = "1";
                    myAO.Tables[2].Cell(rear, 4).Range.Text = lals[k];

                    rear = rear + 1;
                }
                //高锁限力枪
                int toolindex = lals.Count();
                if (nut5 > 0)
                {
                    toolindex = toolindex + 1;
                    myAO.Tables[2].Cell(rear, 1).Range.Text = toolindex.ToString();
                    myAO.Tables[2].Cell(rear, 2).Range.Text = "高锁限力枪\rHI-LITE Istallation Tool";
                    myAO.Tables[2].Cell(rear, 3).Range.Text = "1";
                    myAO.Tables[2].Cell(rear, 4).Range.Text = "KTL1408A218B062";
                    toolindex += 1;
                    rear      += 1;
                }

                if (nut6 > 0)
                {
                    toolindex = toolindex + 1;
                    myAO.Tables[2].Cell(rear, 1).Range.Text = toolindex.ToString();
                    myAO.Tables[2].Cell(rear, 2).Range.Text = "高锁限力枪\rHI-LITE Istallation Tool";
                    myAO.Tables[2].Cell(rear, 3).Range.Text = "1";
                    myAO.Tables[2].Cell(rear, 4).Range.Text = "KTL1439A249C078";
                    rear += 1;
                }


                //寻找图纸列表
                while (!myAO.Tables[2].Cell(rear, 1).Range.Text.Contains("图纸列表"))
                {
                    rear = rear + 1;
                }

                rear = rear + 2;



                //添加图纸

                myAO.Tables[2].Cell(rear, 1).Range.Text = "1";
                myAO.Tables[2].Cell(rear, 2).Range.Text = rncaao["装配图号"];
                myAO.Tables[2].Cell(rear, 3).Range.Text = rncaao["中文名称"] + "壁板组件\r" + rncaao["图纸名称"];



                //寻找程序列表
                while (!myAO.Tables[2].Cell(rear, 1).Range.Text.Contains("程序列表"))
                {
                    rear = rear + 1;
                }

                rear = rear + 2;

                myAO.Tables[2].Cell(rear, 1).Range.Text = "1";
                myAO.Tables[2].Cell(rear, 2).Range.Text = rncaao["程序编号"];

                //替换所有程序编号
                wordMethod.SearchReplace(wordApp, myAO, "MA10016A", rncaao["程序编号"]);


                rear = rear + 1;



                //寻找参考文件列表
                while (!myAO.Tables[2].Cell(rear, 1).Range.Text.Contains("参考文件列表"))
                {
                    rear = rear + 1;
                }

                rear = rear + 8;

                myAO.Tables[2].Cell(rear, 2).Range.Text = rncaao["状态编号"];

                //替换所有状态编号
                wordMethod.SearchReplace(wordApp, myAO, "C1-S22100-33", rncaao["状态编号"]);



                myAO.Tables[2].Cell(rear, 3).Range.Text = rncaao["中文名称"] + "壁板装配交付状态\rCOS OF " + rncaao["图纸名称"];
            }



            myAO.Save();
            //   wordApp.Quit();
            FormMethod.scanfiledoc(rncaao["AOI保存地址"], myAO);
            MessageBox.Show("生成完毕,请补全其他信息");



            return(myAO);
        }
        private void CreateWordDocument(object filename, object savaAs)
        {
            List <Pallet> listPallet = new List <Pallet>();

            switch (Display.Mode)
            {
            case "Real Time": listPallet = Pallet.ListPallet; break;

            case "Simulation": listPallet = Pallet.SimListPallet; break;
            }

            object missing = System.Reflection.Missing.Value;

            MSWord.Application wordApp = new MSWord.Application();

            MSWord.Document myWordDoc = null;

            if (System.IO.File.Exists((string)filename))
            {
                DateTime today = DateTime.Now;

                object readOnly  = false; //default
                object isVisible = false;

                wordApp.Visible = false;

                myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing, ref missing);

                myWordDoc.Activate();

                //Find and replace:
                this.FindAndReplace(wordApp, "<name>", txbName.Text);
                this.FindAndReplace(wordApp, "<phone number>", txbPhoneNumber.Text);
                this.FindAndReplace(wordApp, "<date>", DateTime.Now.ToString("dddd, MMMM dd, yyyy h:mm:ss tt"));
                this.FindAndReplace(wordApp, "<email>", txbEmail.Text);
                this.FindAndReplace(wordApp, "<count>", listPallet.Count);
                this.FindAndReplace(wordApp, "<p>", (listPallet.Count) / 72.0f * 100.0f);

                MSWord.Table table = myWordDoc.Tables[1];
                for (int i = 0; i < listPallet.Count; i++)
                {
                    table.Cell(i + 2, 1).Range.Text = (i + 1).ToString();
                    table.Cell(i + 2, 2).Range.Text = listPallet[i].Code;
                    table.Cell(i + 2, 3).Range.Text = listPallet[i].StoreTime;
                    table.Cell(i + 2, 4).Range.Text = listPallet[i].AtBlock + "-" + listPallet[i].AtColumn + "-" + listPallet[i].AtLevel;
                    if (i != listPallet.Count - 1)
                    {
                        table.Rows.Add(missing);
                    }
                }
            }
            else
            {
                MessageBox.Show("File dose not exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //Save as: filename
            myWordDoc.SaveAs2(ref savaAs, ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing);

            myWordDoc.Close(ref missing, ref missing, ref missing);
            wordApp.Quit(ref missing, ref missing, ref missing);

            MessageBox.Show("File is created at:\n" + savaAs, "", MessageBoxButtons.OK, MessageBoxIcon.Information);

            txbTemplatePath.Clear();
            rtxbTemplate.Clear();
        }
Example #41
0
        public void datosaword2(object sender, DoWorkEventArgs e)
        {
            CreandoInterna = true;
            ListaCodigos = new List<CamposCodigos>();
            CamposCodigos CampoCodigo;
            try
            {
                matarProcesosWordExcel();
                int ContadorEtiquetas = 1;
                foreach (KeyValuePair<int, int> TipyVarEtqs in TodasLasEtiquetasFinales)
                {
                    File.Copy(@rutasEnModAdmin.RutaDePlantillas + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx", @rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx");
                    appWord = new Word.Application();
                    appWord.Visible = false;
                    bool bandera = false;
                    doc = appWord.Documents.Open(@rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx");

                    foreach (Word.Shape s in doc.Shapes)
                    {
                        bandera = false;
                        if (s.Type.ToString() == "msoTextBox")
                        {
                            s.Name = s.Name.Trim();
                            if (s.Name == "txtC1")
                            {
                                s.TextFrame.TextRange.Text = "";
                                continue;
                            }
                            if (s.Name == "txtC2")
                            {
                                s.TextFrame.TextRange.Text = "";
                                continue;
                            }
                            if (s.Name == "txtCAJAS")
                            {
                                s.TextFrame.TextRange.Text = cantidadcajastemporal.ToString();
                                continue;
                            }
                            if (s.Name == "txtCONCATENADO1")
                            {
                                string GCAS = "", QUANTITY = "";
                                foreach (Campos c1 in ListaFinal)
                                {
                                    if (c1.nombrecampo == "txtIRMSGCAS")
                                    {
                                        GCAS = c1.datocampo;
                                    }
                                    if (c1.nombrecampo == "txtQUANTITY")
                                    {
                                        QUANTITY = c1.datocampo;
                                    }
                                }
                                string verificar = etq.UnidadPesos, Unidades = "";
                                verificar = verificar.Substring(verificar.Length - 1);
                                if (verificar == ".")
                                {
                                    Unidades = etq.UnidadPesos.Remove(etq.UnidadPesos.Length - 1);
                                }
                                else
                                {
                                    Unidades = etq.UnidadPesos;
                                }
                                string ConcatenadoTotal = "", ConcatenadoTotal2 = "";
                                ConcatenadoTotal = "91" + GCAS + "37" + QUANTITY + " " + Unidades;
                                ConcatenadoTotal2 = "(91)" + GCAS + "(37)" + QUANTITY + " " + Unidades;
                                s.TextFrame.TextRange.Text = ConcatenadoTotal2;
                                string nombrecampo2 = s.Name.Replace("txt", "bcd");
                                campocodigo.nombrecodigo = nombrecampo2;
                                campocodigo.datocodigo = ConcatenadoTotal;
                                campocodigo.tipocodigo = 128;
                                ListaCodigos.Add(campocodigo);
                            }
                            if (s.Name == "txtCONCATENADO2")
                            {
                                string LOT = "", PALLETTY = "";
                                foreach (Campos c1 in ListaFinal)
                                {
                                    if (c1.nombrecampo == "txtLOT")
                                    {
                                        LOT = c1.datocampo;
                                    }
                                    if (c1.nombrecampo == "txtPALLETTYPE")
                                    {
                                        PALLETTY = c1.datocampo;
                                    }
                                }
                                string ConcatenadoTotal = "", ConcatenadoTotal2 = "";
                                ConcatenadoTotal = "10" + LOT + "90NONE";
                                ConcatenadoTotal2 = "(10)" + LOT + "(90)NONE";
                                s.TextFrame.TextRange.Text = ConcatenadoTotal2;
                                string nombrecampo2 = s.Name.Replace("txt", "bcd");
                                campocodigo.nombrecodigo = nombrecampo2;
                                campocodigo.datocodigo = ConcatenadoTotal;
                                campocodigo.tipocodigo = 128;
                                ListaCodigos.Add(campocodigo);
                            }
                            foreach (Campos c1 in ListaFinal)
                            {
                                if (s.Name == c1.nombrecampo)
                                {
                                    if (diccionario_propiedadesEtq.Keys.Contains(c1.nombrecampo))
                                    {
                                        if (diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.PesoNeto" || diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.PesoBruto" || diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.Tara")
                                        {
                                            s.TextFrame.TextRange.Text = c1.datocampo + " " + etq.UnidadPesos;
                                            bandera = true;
                                            break;
                                        }
                                        if (diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.ClaveProducto" && TipyVarEtqs.Key == 6 && TipyVarEtqs.Value == 1 && etq.Cliente.ToUpper().Contains("ORAL-B"))
                                        {
                                            if (c1.datocampo.Contains('-'))
                                            {
                                                if (c1.datocampo.Split('-').Length > 3)
                                                {
                                                    s.TextFrame.TextRange.Text = "VARIOS";
                                                    bandera = true;
                                                    break;
                                                }
                                            }
                                            else
                                            {
                                                s.TextFrame.TextRange.Text = c1.datocampo;
                                                bandera = true;
                                                break;
                                            }
                                        }
                                        else if (diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.Direccion")
                                        {
                                            string caadenadireccion = "", cadenaanterior = "";
                                            if (c1.datocampo == null)
                                            {
                                                s.TextFrame.TextRange.Text = "";
                                            }
                                            else
                                            {
                                                if (c1.datocampo.Contains("|"))
                                                {
                                                    separadordireccion = c1.datocampo.Split(new string[] { "|" }, StringSplitOptions.None);
                                                    foreach (string str in separadordireccion)
                                                    {
                                                        if (caadenadireccion == "")
                                                        {
                                                            cadenaanterior = str.Remove(0, 4);
                                                            caadenadireccion = cadenaanterior;
                                                        }
                                                        else
                                                            caadenadireccion = caadenadireccion + "\n" + str.Remove(0, 1);
                                                    }
                                                }
                                                else
                                                {
                                                    if (c1.datocampo == "")
                                                        caadenadireccion = "";
                                                    else
                                                        caadenadireccion = c1.datocampo.Remove(0, 4);
                                                }
                                                s.TextFrame.TextRange.Text = caadenadireccion;
                                            }
                                            bandera = true;
                                            break;
                                        }
                                        else
                                        {
                                            s.TextFrame.TextRange.Text = c1.datocampo;
                                            bandera = true;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        s.TextFrame.TextRange.Text = c1.datocampo;
                                        bandera = true;
                                        break;
                                    }
                                }
                            }
                            if (bandera)
                                continue;
                            if (s.TextFrame.TextRange.Text.Contains("PALLET"))
                            {
                                if (cbx_PAQUETE.Checked)
                                {
                                    if (etq.IdiomaETQ == 2)
                                        s.TextFrame.TextRange.Text = s.TextFrame.TextRange.Text.Replace("PALLET", "PACKAGE");
                                    if (etq.IdiomaETQ == 1)
                                        s.TextFrame.TextRange.Text = s.TextFrame.TextRange.Text.Replace("PALLET", "PAQUETE");
                                }
                                continue;
                            }
                        }
                    }
                    foreach (CamposCodigos cmp in ListaCodigosBaseDeDatos)
                    {
                        string nombrecampo = cmp.nombrecodigo.Replace("bcd", "txt");
                        foreach (Campos camps in ListaFinal)
                        {
                            if (camps.nombrecampo == nombrecampo)
                            {
                                CampoCodigo.nombrecodigo = cmp.nombrecodigo;
                                CampoCodigo.datocodigo = camps.datocampo;
                                CampoCodigo.tipocodigo = cmp.tipocodigo;
                                ListaCodigos.Add(CampoCodigo);
                                continue;
                            }
                        }
                    }
                    insertarCodigosDeBarraAWord(doc);
                    if (File.Exists(@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf"))
                        File.Delete((@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf"));
                    doc.ExportAsFixedFormat(@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf", Word.WdExportFormat.wdExportFormatPDF,
                    OptimizeFor: Word.WdExportOptimizeFor.wdExportOptimizeForPrint,
                    BitmapMissingFonts: true, DocStructureTags: false);
                    doc.SaveAs2(@rutasEnModAdmin.RutaDeTemp + "/docTemp.docx");
                    doc.Saved = true;
                    ((Microsoft.Office.Interop.Word._Document)doc).Close();
                    ((Microsoft.Office.Interop.Word._Application)appWord).Quit();
                    File.Delete(@rutasEnModAdmin.RutaDeTemp + "/docTemp.docx");
                    File.Delete(@rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx");
                    ContadorEtiquetas++;
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.matarProcesosWordExcel();
            }
        }
Example #42
0
 private static void WriteWord(string filename)
 {
     Word.Application word = null;
     Word.Document    doc  = null;
     try {
         word         = new Word.Application();
         word.Visible = false;
         doc          = word.Documents.Add(Visible: false);
         {
             Word.PageSetup ps = doc.PageSetup;
             ps.Orientation = Word.WdOrientation.wdOrientLandscape;
             ps.TopMargin   = ps.BottomMargin = ps.LeftMargin = ps.RightMargin = word.InchesToPoints(0.5f);
             Word.TextColumns ts = ps.TextColumns;
             ts.SetCount(4);
         }
         int            columnLines = 0;
         Word.Paragraph p           = null;
         foreach (Household h in Households)
         {
             int    paraLines = 2;
             string content   = h.Name;
             if (h.Phone != "")
             {
                 ++paraLines;
                 content += String.Format("\vPhone: {0}", h.Phone);
             }
             if (h.Contacts.Count == 1)
             {
                 Contact c = h.Contacts[0];
                 if (c.CellPhone != "")
                 {
                     ++paraLines;
                     content += String.Format("\vCell: {0}", c.CellPhone);
                 }
                 if (c.Email != "")
                 {
                     ++paraLines;
                     content += String.Format("\vEmail: {0}", h.Email);
                 }
                 if (c.WorkEmail != "")
                 {
                     ++paraLines;
                     content += String.Format("\vWork Email: {0}", c.WorkEmail);
                 }
                 //if (c.Birthday.HasValue) {
                 //   ++paraLines;
                 //   content += String.Format("\vBirthday: {0:MMM d}", c.Birthday.Value);
                 //}
             }
             else
             {
                 foreach (Contact c in h.Contacts)
                 {
                     if (c.CellPhone != "")
                     {
                         ++paraLines;
                         content += String.Format("\v{0} Cell: {1}", c.First, c.CellPhone);
                     }
                 }
                 if (h.Email != "")
                 {
                     ++paraLines;
                     content += String.Format("\vEmail: {0}", h.Email);
                 }
                 else
                 {
                     foreach (Contact c in h.Contacts)
                     {
                         if (c.Email != "")
                         {
                             ++paraLines;
                             content += String.Format("\v{0} Email: {1}", c.First, c.Email);
                         }
                     }
                 }
                 foreach (Contact c in h.Contacts)
                 {
                     if (c.WorkEmail != "")
                     {
                         ++paraLines;
                         content += String.Format("\v{0} Work Email: {1}", c.First, c.Email);
                     }
                 }
                 //foreach (Contact c in h.Contacts) {
                 //   if (c.Birthday.HasValue) {
                 //      ++paraLines;
                 //      content += String.Format("\v{0} Birthday: {1:MMM d}", c.First, c.Birthday.Value);
                 //   }
                 //}
             }
             if (h.Address != "")
             {
                 ++paraLines;
                 content += "\vAddress:";
                 foreach (string line in h.Address.Split('\n'))
                 {
                     ++paraLines;
                     content += String.Format("\v\t{0}", line);
                 }
             }
             if (columnLines + paraLines > 50)
             {
                 content     = (char)14 + content;
                 columnLines = paraLines;
             }
             else
             {
                 columnLines += paraLines;
             }
             p                 = doc.Paragraphs.Add();
             p.Range.Text      = content;
             p.Range.Font.Bold = 0;
             p.Range.Font.Size = 8.0f;
             p.TabStops.Add(16.0f);
             doc.Range(p.Range.Start, p.Range.Start + content.IndexOf('\v')).Font.Bold = 1;
             p.Range.InsertParagraphAfter();
         }
         p = doc.Paragraphs.Add();
         p.Range.InsertBreak(Word.WdBreakType.wdPageBreak);
         p.Range.InsertParagraphAfter();
         Dictionary <int, List <Contact> > birthdays = Contacts
                                                       .Where(c => c.Birthday.HasValue)
                                                       .GroupBy(c => c.Birthday.Value.Month)
                                                       .ToDictionary(
             cg => cg.Key,
             cg => cg.OrderBy(c => c.Birthday).ToList()
             );
         foreach (var month in birthdays.OrderBy(k => k.Key))
         {
             string content = month.Value[0].Birthday.Value.ToString("MMMM");
             foreach (Contact c in month.Value.OrderBy(k => k.Birthday.Value.Day))
             {
                 content += String.Format("\v\t{0:MMM-d}: {1}", c.Birthday.Value, c.ShortName);
                 if (c.Birthday.Value < DateTime.Today)
                 {
                     content += String.Format(" ({0})", c.Birthday.Value.Year);
                 }
             }
             p                 = doc.Paragraphs.Last;
             p.Range.Text      = content;
             p.Range.Font.Bold = 0;
             p.Range.Font.Size = 12.0f;
             p.TabStops.Add(16.0f);
             doc.Range(p.Range.Start, p.Range.Start + content.IndexOf('\v')).Font.Bold = 1;
             p.Range.InsertParagraphAfter();
         }
     } finally {
         if (doc != null)
         {
             doc.SaveAs2(FileName: filename);
             doc.Close();
         }
         if (word != null)
         {
             word.Quit();
         }
     }
 }
        private int pasarPrimerosDatosAWord()
        {
            /*CÓDIGOS DE ERRORES (SE REGRESA UN ENTERO EN CADA CASO)
             * return 0: Proceso encontró un error y lanzó Excepción que será desplegada como MessageBox
             * return 1: Proceso ejecutado correctamente. 
             * return -1: Plantilla de word se encontraba abierta en un proceso de windows. Se cierra.
             */
            try
            {
                string path = @rutasEnModAdmin.RutaDePlantillas + "\\Etq_" + etq.TipoEtiqueta.ToString() + "_" + etq.VariacionEtiqueta.ToString() + ".docx"; 
                appWord = new Word.Application();
                appWord.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
                appWord.Visible = false;
                bool isOpen = false;
                FileStream stream = null;
                try
                {
                    stream = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                }
                catch (IOException)
                {
                    isOpen = true;
                }
                finally
                {
                    if (stream != null)
                        stream.Close();
                }
                if (isOpen)
                {
                    Process[] proces = Process.GetProcessesByName("WINWORD");
                    foreach (Process proc in proces)
                    {
                        if (proc.MainWindowTitle == "")
                            proc.Kill();
                    }
                    MessageBox.Show("Existía un proceso abierto, y se ha cerrado correctamente. Favor de intentar nuevamente.", "Proceso Terminado", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return -1;
                }


                doc = appWord.Documents.Open(path);

                List<Word.Shape> lst = new List<Word.Shape>();


                #region insertar en la primera plantilla de word
                foreach (Word.Shape sh in doc.Shapes)
                    if (sh.Type.ToString() == "msoTextBox")
                    {
                        while (sh.Name.Contains("\n"))
                            sh.Name = sh.Name.Replace("\n", "");
                        lst.Add(sh);
                    }

                foreach (Control ctr in gb_CamposAdicionales.Controls)
                {
                    if (ctr.GetType() == typeof(TextBox))
                    {
                        foreach (Word.Shape sh in lst)
                        {
                            if (ctr.Name == sh.Name.Trim())
                            {
                                sh.TextFrame.TextRange.Text = ctr.Text;
                            }
                        }
                    }
                }
                foreach (Control cbox in gb_CamposAdicionales.Controls.OfType<ComboBox>())
                {
                    if (diccionario_propiedadesEtq.ContainsKey(cbox.Name))
                    {
                        if (diccionario_propiedadesEtq[cbox.Name] == "Etiqueta.Direccion")
                        {
                            foreach (Word.Shape sh in lst)
                            {
                                if (cbox.Name == sh.Name.Trim())
                                {
                                    sh.TextFrame.TextRange.Text = etq.Direccion;
                                }
                            }
                        }
                        else if (diccionario_propiedadesEtq[cbox.Name] == "Etiqueta.Embarque")
                        {
                            foreach (Word.Shape sh in lst)
                            {
                                if (cbox.Name == sh.Name.Trim())
                                {
                                    sh.TextFrame.TextRange.Text = etq.Embarque;
                                }
                            }
                        }

                    }
                    else //en este caso estamos hablando del comboBox de unidades de corte 
                    {
                        foreach (Control txtCorte in gb_CamposAdicionales.Controls.OfType<TextBox>())
                        {
                            if (txtCorte.Name != nombreCorte)
                                continue;
                            else
                            {
                                foreach (Word.Shape sh in lst)
                                    if (txtCorte.Name == sh.Name.Trim())
                                    {
                                        etq.Corte = txtCorte.Text + " " + cbox.Text;
                                        sh.TextFrame.TextRange.Text = etq.Corte;
                                    }
                                        
                            }
                        }
                            
                        
                    }
                }

                foreach (Control dt in gb_CamposAdicionales.Controls.OfType<DateTimePicker>())
                {
                    foreach (Word.Shape sh in lst)
                    {
                        if (dt.Name == sh.Name.Trim())
                        {
                            sh.TextFrame.TextRange.Text = dt.Text;
                        }
                    }
                }
                

                #endregion

                //guardamos como plantilla de etiqueta actual
                doc.SaveAs2(@rutasEnModAdmin.RutaDePlantillas + "/temp_EtiquetaActual.docx");
                doc.Saved = true;
                ((Microsoft.Office.Interop.Word._Document)doc).Close();
                return 1;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                return 0;
            }
        }
Example #44
0
        private void WordReplace(Dictionary <string, string> replaceDic, object objFile, object newFile, Word.Application app)
        {
            Word.Document doc = doc = app.Documents.Open(ref objFile,
                                                         ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                                                         ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                                                         ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            bool delete = false;//是否删除源文件

            try
            {
                object replace = Word.WdReplace.wdReplaceAll;
                string from, to;
                if (replaceDic.Count > 0)
                {
                    foreach (var item in replaceDic)
                    {
                        from = item.Key;
                        to   = item.Value;
                        app.Selection.Find.Replacement.ClearFormatting();
                        app.Selection.Find.ClearFormatting();
                        app.Selection.Find.Text             = from; //需要被替换的文本
                        app.Selection.Find.Replacement.Text = to;   //替换文本
                        app.Selection.Find.Execute(
                            ref Nothing, ref Nothing,
                            ref Nothing, ref Nothing,
                            ref Nothing, ref Nothing,
                            ref Nothing, ref Nothing, ref Nothing,
                            ref Nothing, ref replace,
                            ref Nothing, ref Nothing,
                            ref Nothing, ref Nothing);//执行替换操作
                    }
                }

                if (newFile == null || newFile.ToString() == objFile.ToString())
                {
                    doc.Save();
                }
                else
                {
                    doc.SaveAs2(newFile);
                    delete = true;
                }
            }
            catch (Exception ex)
            {
                Log.Error("保存失败!", ex);
            }
            finally
            {
                try { doc.Close(); } catch { }
                if (delete)
                {
                    try
                    {
                        File.Delete(objFile.ToString());
                    }
                    catch (Exception ex)
                    {
                        Log.Error("删除失败!", ex);
                    }
                }
            }
        }
        //создание отчета для ЦА
        private async Task CreateReportCA(string file_path)
        {
            await Task.Run(() =>
            {
                //задаем текст и значения statusStrip
                this.Invoke((Action)delegate
                {
                    tsProgressBar.Value = 0;
                    tsStatusLabel.Text = "Открытие шаблона";
                });
                //берем значения рабочих и дней месяца
                string work_days = settings.tbWorkDays.Text;
                string month_in_days = settings.tbMonthDays.Text;
                //объявляем переменные для подсчета кол-ва работ проводимых каждый день и только в рабочие дни
                int count_work_days = 0;
                int count_month_in_days = 0;
                //создаем документ Word на основе шаблона и делаем его невидимым
                word_app = new Word.Application();
                word_doc = word_app.Documents.Add(file_path);
                word_app.Visible = false;
                //заменяем в документе <Period_month> на период
                WordReplace("<Period_month>", StringPeriod(true));
                //заменяем все <WorkDays> на число рабочих дней, а также подсчитываем их кол-во
                WordReplace("<WorkDays>", work_days, ref count_work_days);
                //также заменяем <MonthInDays> на число дней в месяце, а также посчитываем их кол-во
                WordReplace("<MonthInDays>", month_in_days, ref count_month_in_days);
                //заменяем переменную в документе на текущий период
                dynamic word_vars = word_doc.CustomDocumentProperties;
                dynamic word_var_period = word_vars["_Период"].Value = StringPeriod(true);
                //объявляем массив для дней из таблицы
                var dates_from_table = new List<DateTime>();
                //проход по таблице 
                for (int i = 0; i < dgvTable.Rows.Count; i++)
                {
                    //добавляем в массив каждую дату из таблицы
                    dates_from_table.Add((DateTime)dgvTable.Rows[i].Cells[0].Value);
                }
                //делаем словарь (Dictonary) с ключом - Дата, и значением - число заявок в этот день
                var dates_with_count_tickets = dates_from_table
                    .Select(DateTime => new { Date = DateTime, Count = dates_from_table.Count(d => d == DateTime) })
                    .Where(obj => obj.Count >= 1)
                    .Distinct()
                    .ToDictionary(obj => obj.Date, obj => obj.Count);
                //объявляем зубчатый массив [][,], где [день][кол-во заявок(кол-во строк),строки "дата завершения","номер кабинета","содержание","метод обращения"(кол-во столбцов)]
                object[][,] tickets = new object[dates_with_count_tickets.Count][,];
                //удаляем дубликаты из массива с днями
                dates_from_table = dates_from_table.Distinct().ToList();
                //объявляем перменные для номера дня из зубчатого массива и для индекса строки таблицы
                int day = 0;
                int row = 0;
                //проход по словарю
                foreach (var d in dates_with_count_tickets)
                {
                    //объявляем массив для дня с числом строк
                    tickets[day] = new object[d.Value, 4];
                    //проход по строкам
                    for (int i = 0; i < d.Value; i++)
                    {
                        //по столбцам
                        for (int j = 0; j < 4; j++)
                        {
                            //заносим в массив данные из таблицы
                            tickets[day][i, j] = dgvTable.Rows[row].Cells[j].Value.ToString();
                        }
                        //переход на след строку
                        row++;
                    }
                    //след день
                    day++;
                }
                //объвляем переменную для второй таблицы
                word_table2 = word_doc.Tables[2];
                // ищем последную ячейку
                Word.Cell last_cell = word_table2.Range.Cells[word_table2.Range.Cells.Count];
                // первая ячейка в последней строке
                Word.Cell cell_position_to_insert_rows = word_table2.Cell(last_cell.RowIndex, 1);
                // индекс строки, в которую будут записываться данные
                int row_to_insert_tickets = cell_position_to_insert_rows.RowIndex;
                // строка которая должна быть раскрашена
                int row_to_color = row_to_insert_tickets + 1;
                // индекс массива с определенным днем
                int number_of_massive = 0;
                // индекс ячейки, с которой необходимо начать объединять ячейки в первом столбце
                int row_start_merge = row_to_insert_tickets;
                // объявление переменной для подсчета кол-во плановых работ
                int tickets_planovie = 0;
                // переменная для подсчета обращений
                int tickets_obrascheniya = 0;
                // вставка необходимого кол-ва строк, -1 - т.к. 1 пустая строка уже вставлена
                for (int i = 0; i < dgvTable.Rows.Count - 1; i++)
                {
                    cell_position_to_insert_rows.Range.Rows.Add();
                    this.Invoke((Action)delegate
                    {
                        tsStatusLabel.Text = "Вставка строк";
                        tsProgressBar.Maximum = dgvTable.Rows.Count-1;
                        tsProgressBar.Value++;
                    });
                }
                this.Invoke((Action)delegate
                {
                    tsStatusLabel.Text = "Заполнение документа";
                    tsProgressBar.Value = 0;
                });
                // проход по массиву
                for (int i = 0; i < tickets.Length; i++)
                {
                    // первая ячейка в строке - дата
                    DateTime first_cell_in_row = (DateTime)Convert.ChangeType(tickets[number_of_massive][0, 0], typeof(DateTime));
                    // вставляем дату в документ
                    word_table2.Cell(row_to_insert_tickets, 1).Range.Text = first_cell_in_row.ToString("dd.MM.yyyy");
                    // проход по заявкам в каждом дне
                    for (int j = 0; j < tickets[number_of_massive].GetLength(0); j++)
                    {
                        //вставляем в таблицу данные из массива
                        word_table2.Cell(row_to_insert_tickets, 2).Range.Text = tickets[number_of_massive][j, 1].ToString();
                        word_table2.Cell(row_to_insert_tickets, 3).Range.Text = tickets[number_of_massive][j, 2].ToString();
                        word_table2.Cell(row_to_insert_tickets, 4).Range.Text = tickets[number_of_massive][j, 3].ToString();
                        // подсчитываем плановые
                        if (word_table2.Cell(row_to_insert_tickets, 4).Range.Text.Contains("Плановые работы"))
                        {
                            tickets_planovie++;
                        }
                        // если не плановые, то увеличиваем обращения
                        else tickets_obrascheniya++;
                        // переходим на след строку в документе
                        row_to_insert_tickets++;
                    }
                    // если строки не равны, то объеденияем ячейки
                    if (!(row_start_merge == row_to_insert_tickets - 1))
                    {
                        word_table2.Cell(row_start_merge, 1).Merge(word_table2.Cell(row_to_insert_tickets - 1, 1));
                    }
                    // переходим к след дню
                    row_start_merge = row_to_insert_tickets;
                    number_of_massive++;
                    this.Invoke((Action)delegate
                    {
                        tsStatusLabel.Text = "Заполнение документа";
                        tsProgressBar.Maximum = tickets.Length;
                        tsProgressBar.Value++;
                    });
                }
                // объявляем переменную для первой таблицы, в которую пишутся итоги
                word_table1 = word_doc.Tables[1];
                // берем все месячные работы из начала документа
                int planovie_calendar = ((int.Parse(work_days) * count_work_days) + (int.Parse(month_in_days) * count_month_in_days));
                // пишем кол-во обращений
                word_table1.Rows[2].Cells[2].Range.Text = tickets_obrascheniya.ToString();
                // пишем кол-во плановых работ
                word_table1.Rows[3].Cells[2].Range.Text = (planovie_calendar + tickets_planovie).ToString();
                // пишем общее кол-во заявок
                word_table1.Rows[4].Cells[2].Range.Text = (planovie_calendar + tickets_planovie + tickets_obrascheniya).ToString();
                // цвет для закраски чередующихся строк
                Color color_background = Color.FromArgb(222, 234, 246);
                // приводим цвет к совместимому с Word
                var word_background_color = (Microsoft.Office.Interop.Word.WdColor)(color_background.R + 0x100 * color_background.G + 0x10000 * color_background.B); ;
                // закрашиваем каждую вторую строку
                while (row_to_color < row_to_insert_tickets)
                {
                    word_table2.Cell(row_to_color, 2).Shading.BackgroundPatternColor = word_background_color;
                    word_table2.Cell(row_to_color, 3).Shading.BackgroundPatternColor = word_background_color;
                    word_table2.Cell(row_to_color, 4).Shading.BackgroundPatternColor = word_background_color;
                    row_to_color += 2;
                }

                this.Invoke((Action)delegate
                {
                    tsProgressBar.Value = 0;
                    tsStatusLabel.Text = "Готово!";
                    // окно сохранения документа
                    SaveFileDialog sfd = new SaveFileDialog();
                    // расширение по умеолчанию
                    sfd.DefaultExt = "docx";
                    // автоматом добавлять расширение
                    sfd.AddExtension = true;
                    // фильтр выводимых файлов в окне
                    sfd.Filter = "Документ Word(*.docx)|*.docx";
                    // фильтр по умолчанию
                    sfd.FilterIndex = 1;
                    // задаем имя документу
                    sfd.FileName = "Еженедельный-Месячный отчет " + StringPeriod(false);
                    // при нажатии "ОК"
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        // сохраняем документ
                        word_doc.SaveAs2(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                        // выводим окно с сообщением
                        MessageBox.Show("Готово!\nСхоранено в "+sfd.FileName);
                        // закрываем документ с сохранием
                        word_doc.Close(Word.WdSaveOptions.wdSaveChanges, Type.Missing, Type.Missing);
                        // закрываем приложение Word
                        word_app.Quit(Type.Missing, Type.Missing, Type.Missing);
                        // прибиваем процесс Word'a
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(word_app);
                        // сбрасываем ссылки на Word
                        word_doc = null;
                        word_app = null;
                        // пробуем удалить из памяти лишнее
                        GC.Collect();
                    }
                    // при любом другом действии
                    else
                    {
                        // закрываем документ без сохранения
                        word_doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Type.Missing, Type.Missing);
                        // закрываем приложение без сохранения
                        word_app.Quit(Word.WdSaveOptions.wdDoNotSaveChanges, Type.Missing, Type.Missing);
                        // убаваем процесс
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(word_app);
                        // сбрасываем ссылки
                        word_doc = null;
                        word_app = null;
                        // запуск сборщика мусора
                        GC.Collect();
                    }
                });


            });
        }
        private void CreateDocument()
        {
            try
            {
                //Save location
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.DefaultExt       = ".docx";
                saveFileDialog1.Filter           = "Word|*.docx";
                saveFileDialog1.AddExtension     = true;
                saveFileDialog1.InitialDirectory = @"C:\Desktop";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    object filename = saveFileDialog1.FileName;
                    //Create an instance for word
                    Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

                    //Set animation status for word application
                    winword.ShowAnimation = false;

                    //Set status for word application is to be visible or not.
                    winword.Visible = false;

                    //Create a missing variable for missing value
                    object missing = System.Reflection.Missing.Value;

                    //Create a new document
                    Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                    //Add paragraph with Heading 1 style
                    Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);

                    //Create a table
                    int rows    = printC_dgv.Rows.Count + 1;
                    int columns = printC_dgv.Columns.Count;

                    Table T = document.Tables.Add(para1.Range, rows, columns, ref missing, ref missing);

                    T.Borders.Enable = 1;

                    //Insert
                    for (int i = 1; i < T.Rows.Count - 1; i++)
                    {
                        for (int j = 1; j < T.Columns.Count + 1; j++)
                        {
                            //Header
                            T.Rows[1].Cells[j].Range.Text      = printC_dgv.Columns[j - 1].HeaderText.ToString();
                            T.Rows[1].Cells[j].Range.Font.Bold = 1;
                            T.Rows[1].Cells[j].Range.Font.Name = "verdana";
                            T.Rows[1].Cells[j].Range.Font.Size = 10;
                            T.Rows[1].Cells[j].Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                            T.Rows[1].Cells[j].VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            T.Rows[1].Cells[j].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                            //Data
                            T.Rows[i + 1].Cells[j].Range.Text = printC_dgv.Rows[i - 1].Cells[j - 1].Value.ToString();
                        }
                    }
                    foreach (Microsoft.Office.Interop.Word.Section section in T.Application.ActiveDocument.Sections)
                    {
                        Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                        headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                        headerRange.Text      = "List Courses of HCMC UTE";
                        headerRange.Font.Size = 24;
                        headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    }

                    document.SaveAs2(ref filename);
                    document.Close(ref missing, ref missing, ref missing);
                    document = null;
                    winword.Quit(ref missing, ref missing, ref missing);
                    winword = null;
                    MessageBox.Show("Document created successfully !");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #47
0
        private void button2_Click(object sender, EventArgs e)
        {
            var filePath = AppDomain.CurrentDomain.BaseDirectory + "test.dotx";//文档路径
            Word.Application appWord = new Word.Application();
            Word.Document doc = new Word.Document();
            object oMissing = System.Reflection.Missing.Value;
            //打开模板文档,并指定doc的文档类型
            object objTemplate = filePath;
            object objDocType = Word.WdDocumentType.wdTypeDocument;
            object objFalse = false;
            object objTrue = true;
            doc = (Word.Document)appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);

            foreach (Word.ContentControl item in appWord.ActiveDocument.ContentControls)
            {
                if (item.Tag == "Information")
                {
                    item.Range.Text = "紫川软件测试";

                }
            }

            object savePath = AppDomain.CurrentDomain.BaseDirectory + "test1.docx";   //文档另存为的路径
            object missingValue = Type.Missing;
            object miss = System.Reflection.Missing.Value;
            object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
            doc.SaveAs2(ref savePath);
            doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
            appWord.Application.Quit(ref miss, ref miss, ref miss);
            doc = null;
            appWord = null;
        }
        public void datosaword(object sender, DoWorkEventArgs e)
        {
            try
            {
                matarProcesosWordExcel();
                int ContadorEtiquetas = 1;
                foreach (KeyValuePair<int, int> TipyVarEtqs in Tipospalletfinal)
                {
                    ListaCodigos = new List<CamposCodigos>();
                    CamposCodigos CampoCodigo;
                    File.Copy(@rutasEnModAdmin.RutaDePlantillas + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx", @rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx");
                    appWord = new Word.Application();
                    appWord.Visible = false;
                    bool bandera = false;
                    doc = appWord.Documents.Open(@rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx");

                    foreach (Word.Shape s in doc.Shapes)
                    {
                        bandera = false;
                        if (s.Type.ToString() == "msoTextBox")
                        {
                            s.Name = s.Name.Trim();
                            foreach (Campos c1 in ListaFinal)
                            {
                                if (s.Name == c1.nombrecampo)
                                {
                                    if (diccionario_propiedadesEtq.Keys.Contains(c1.nombrecampo))
                                    {
                                        if (diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.PesoNeto" || diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.PesoBruto" || diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.Tara")
                                        {
                                            s.TextFrame.TextRange.Text = c1.datocampo + " " + unidadeS;
                                            bandera = true;
                                            break;
                                        }
                                        else if (diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.Direccion")
                                        {
                                            string caadenadireccion = "", cadenaanterior = "";
                                            if (c1.datocampo == null)
                                            {
                                                s.TextFrame.TextRange.Text = "";
                                            }
                                            else
                                            {
                                                if (c1.datocampo.Contains("|"))
                                                {
                                                    separadordireccion = c1.datocampo.Split(new string[] { "|" }, StringSplitOptions.None);
                                                    foreach (string str in separadordireccion)
                                                    {
                                                        if (caadenadireccion == "")
                                                        {
                                                            cadenaanterior = str.Remove(0,4);
                                                            caadenadireccion = cadenaanterior;
                                                        }
                                                        else
                                                            caadenadireccion = caadenadireccion + "\n" + str.Remove(0,1);
                                                    }
                                                }
                                                else
                                                {
                                                    if (c1.datocampo == "")
                                                        caadenadireccion = "";
                                                    else
                                                        caadenadireccion = c1.datocampo.Remove(0,4);
                                                }
                                                s.TextFrame.TextRange.Text = caadenadireccion;
                                            }
                                            bandera = true;
                                            break;
                                        }
                                        else
                                        {
                                            if (s.Name == "txtPRODUCTCODE" || s.Name == "txtORDERNO")
                                            {
                                                if (c1.datocampo.Length > 29)
                                                    s.TextFrame.TextRange.Font.Size = s.TextFrame.TextRange.Font.Size - 10;
                                                if (c1.datocampo.Length > 34)
                                                    s.TextFrame.TextRange.Font.Size = s.TextFrame.TextRange.Font.Size - 10;
                                                if (c1.datocampo.Length > 41)
                                                    s.TextFrame.TextRange.Font.Size = s.TextFrame.TextRange.Font.Size - 5;
                                                if (c1.datocampo.Length > 70)
                                                    s.TextFrame.TextRange.Font.Size = s.TextFrame.TextRange.Font.Size - 5;
                                            }
                                            s.TextFrame.TextRange.Text = c1.datocampo;
                                            bandera = true;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        s.TextFrame.TextRange.Text = c1.datocampo;
                                        bandera = true;
                                        break;
                                    }
                                }
                            }
                            if (bandera)
                                continue;
                            if (s.TextFrame.TextRange.Text.Contains("PALLET"))
                            {
                                if (cbx_PAQUETE.Checked)
                                {
                                    if (etq.IdiomaETQ == 2)
                                        s.TextFrame.TextRange.Text = s.TextFrame.TextRange.Text.Replace("PALLET", "PACKAGE");
                                    if (etq.IdiomaETQ == 1)
                                        s.TextFrame.TextRange.Text = s.TextFrame.TextRange.Text.Replace("PALLET", "PAQUETE");
                                }
                                continue;
                            }
                        }
                    }
                    foreach (CamposCodigos cmp in ListaCodigosBaseDeDatos)
                    {
                        string nombrecampo = cmp.nombrecodigo.Replace("bcd", "txt");
                        foreach (Campos camps in ListaFinal)
                        {
                            if (camps.nombrecampo == nombrecampo)
                            {
                                CampoCodigo.nombrecodigo = cmp.nombrecodigo;
                                CampoCodigo.datocodigo = camps.datocampo;
                                CampoCodigo.tipocodigo = cmp.tipocodigo;
                                ListaCodigos.Add(CampoCodigo);
                                continue;
                            }
                        }
                    }
                    insertarCodigosDeBarraAWord(doc);
                    if (File.Exists(@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf"))
                        File.Delete((@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf"));
                    doc.ExportAsFixedFormat(@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf", Word.WdExportFormat.wdExportFormatPDF,
                    OptimizeFor: Word.WdExportOptimizeFor.wdExportOptimizeForPrint,
                    BitmapMissingFonts: true, DocStructureTags: false);
                    doc.SaveAs2(@rutasEnModAdmin.RutaDeTemp + "/docTemp.docx");
                    doc.Saved = true;
                    ((Microsoft.Office.Interop.Word._Document)doc).Close();
                    ((Microsoft.Office.Interop.Word._Application)appWord).Quit();
                    File.Delete(@rutasEnModAdmin.RutaDeTemp + "/docTemp.docx");
                    File.Delete(@rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx");
                    ContadorEtiquetas++;
                    //}
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.matarProcesosWordExcel();
            }
        }