Esempio n. 1
0
        private void button4_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

            object missing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Document doc = app.Documents.Add();

            doc.Content.SetRange(0, 0);

            //Doc파일에 제목
            Microsoft.Office.Interop.Word.Paragraph para1 = doc.Content.Paragraphs.Add(ref missing);
            //object styleHeading1 = "Heading 1";
            //para1.Range.set_Style(ref styleHeading1);
            para1.Range.Text = "인맥 정보";
            para1.Range.InsertParagraphAfter();

            //Doc파일에 테이블생성
            Microsoft.Office.Interop.Word.Table table;
            table = doc.Tables.Add(para1.Range, 2, 2, ref missing, ref missing);
            table.Borders.Enable = 1;

            //Doc파일에 테이블입력
            table.Cell(1, 1).Range.Text = "이름";
            table.Cell(1, 2).Range.Text = "내용";
            table.Cell(2, 1).Range.Text = textBox6.Text;
            table.Cell(2, 2).Range.Text = textBox2.Text;


            object filename = @"C:\Users\J\Desktop\personal connection.docx";

            doc.SaveAs2(ref filename);
            doc.Close();
        }
Esempio n. 2
0
        private void CreateDoc(string name)
        {
            Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

            winword.Visible = true;

            object missing = System.Reflection.Missing.Value;

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


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

            para1.Range.Font.Size = 20;
            para1.Range.Bold      = 1;
            para1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            para1.Range.Text = name + (dt.Rows[0] as DataRow).Field <int>(Convert.ToString(dt.Columns[0].ToString()).ToString());

            para1.Range.InsertParagraphAfter();
            Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);

            for (int i = 2; i < dt.Columns.Count; i++)
            {
                para2.Range.Text += (dt.Rows[0] as DataRow).Field <string>(Convert.ToString(dt.Columns[i].ToString()).ToString());
            }
            para2.Range.InsertParagraphAfter();
        }
Esempio n. 3
0
        public void Render(Microsoft.Office.Interop.Word.Table table)
        {
            table.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            table.Range.Font.Name          = "Calibri";

            // 填入表格資料
            int rowIndex = 1;

            foreach (DataRow row in MyDataTable.Rows)
            {
                ////table.Cell(rowIndex, 1).Range.Font.Bold = 1;
                ////table.Cell(rowIndex, 1).Range.Text = string.Format("{0}{1}({2})",
                ////    row["Project"].ToString(),
                ////    Environment.NewLine,
                ////    row["Skus"].ToString());

                Microsoft.Office.Interop.Word.Range range = table.Cell(rowIndex, 1).Range;

                Microsoft.Office.Interop.Word.Paragraph p1 = range.Paragraphs.Add(range);
                p1.Range.Font.Bold = 0;
                p1.Range.Font.Size = 10;
                p1.Range.Text      = string.Format("({0})", row["Skus"].ToString());

                Microsoft.Office.Interop.Word.Paragraph p2 = range.Paragraphs.Add(range);
                p2.Range.Font.Bold = 1;
                p2.Range.Font.Size = 12;
                p2.Range.Text      = row["Project"].ToString() + Environment.NewLine;

                rowIndex++;
            }
        }
        private void ImprimeDocumento(TreeViewItem item)
        {
            Microsoft.Office.Interop.Word.Paragraph par = oDoc.Content.Paragraphs.Add(ref oMissing);

            foreach (TreeViewItem child in item.Items)
            {
                Temas tema = (Temas)child.Tag;

                par.Range.Font.Bold = 0;
                par.Range.Font.Size = 10;
                par.Range.Font.Name = "Arial";

                if (tema.Nivel == 0)
                {
                    par.Range.Text = tema.Tema;
                }
                else if (tema.Nivel == 1)
                {
                    par.Range.Text = "     " + tema.Tema;
                }
                else if (tema.Nivel == 2)
                {
                    par.Range.Text = "          " + tema.Tema;
                }
                else if (tema.Nivel == 3)
                {
                    par.Range.Text = "               " + tema.Tema;
                }

                par.Range.InsertParagraphAfter();

                ImprimeDocumento(child);
            }
        }
Esempio n. 5
0
        public void print_report_2(DataTable dt, DateTime d1, DateTime d2)
        {
            try
            {
                object missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Document report_file = win_word.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                Microsoft.Office.Interop.Word.Paragraph para1 = report_file.Content.Paragraphs.Add(ref missing);
                para1.Range.Text = String.Format("Отчет с {0} по {1}", d1.ToShortDateString(), d2.ToShortDateString());
                para1.Range.InsertParagraphAfter();

                Microsoft.Office.Interop.Word.Table data_table = report_file.Tables.Add(para1.Range, dt.Rows.Count + 1, 9, ref missing, ref missing);
                data_table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                data_table.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                data_table.Cell(1, 1).Range.Text    = "Дата";
                data_table.Cell(1, 2).Range.Text    = "ФИО клиента";
                data_table.Cell(1, 3).Range.Text    = "Код услуги";
                data_table.Cell(1, 4).Range.Text    = "Цена";
                data_table.Cell(1, 5).Range.Text    = "Скидка";
                data_table.Cell(1, 6).Range.Text    = "Итог";
                data_table.Cell(1, 7).Range.Text    = "Доктор";
                data_table.Cell(1, 8).Range.Text    = "Доля";
                data_table.Cell(1, 9).Range.Text    = "Админ";
                //logs(date datetime default CURRENT_TIMESTAMP, name text, service_code int, price int, discount int, final int, doctorcode text, share int, login text);");
                //fill table
                int index = 2;

                foreach (DataRow dr in dt.Rows)
                {
                    data_table.Cell(index, 1).Range.Text = dr["date"].ToString();
                    data_table.Cell(index, 2).Range.Text = dr["name"].ToString();
                    data_table.Cell(index, 3).Range.Text = dr["service_code"].ToString();
                    data_table.Cell(index, 4).Range.Text = dr["price"].ToString();
                    data_table.Cell(index, 5).Range.Text = dr["discount"].ToString();
                    data_table.Cell(index, 6).Range.Text = dr["final"].ToString();
                    data_table.Cell(index, 7).Range.Text = dr["doctorcode"].ToString();
                    data_table.Cell(index, 8).Range.Text = dr["share"].ToString();
                    data_table.Cell(index, 9).Range.Text = dr["login"].ToString();
                    index++;
                }
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();

                saveFileDialog1.Filter           = "doc files (*.docx)|*.docx|All files (*.*)|*.*";
                saveFileDialog1.FilterIndex      = 1;
                saveFileDialog1.RestoreDirectory = true;
                object file_path = "";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    file_path = saveFileDialog1.FileName;
                }

                report_file.SaveAs2(ref file_path);
                report_file.Close(ref missing, ref missing, ref missing);
                report_file = null;
                MessageBox.Show("Document created successfully !");
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
        public int GeneraWord()
        {
            oWord = new Microsoft.Office.Interop.Word.Application();
            oDoc  = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            try
            {
                foreach (TreeViewItem item in treeView.Items)
                {
                    Microsoft.Office.Interop.Word.Paragraph par = oDoc.Content.Paragraphs.Add(ref oMissing);

                    par.Range.Font.Bold = 0;
                    par.Range.Font.Size = 10;
                    par.Range.Font.Name = "Arial";
                    par.Range.Text      = item.Header.ToString();
                    par.Range.InsertParagraphAfter();

                    ImprimeDocumento(item);
                }



                /* //Agregando esto para guardar hasta el inicio del catch
                 * SaveFileDialog CuadroDialogo = new SaveFileDialog();
                 * CuadroDialogo.DefaultExt = "docx";
                 * CuadroDialogo.Filter = "docx file(*.docx)|*.docx";
                 * CuadroDialogo.AddExtension = true;
                 * CuadroDialogo.RestoreDirectory = true;
                 * CuadroDialogo.Title = "Guardar";
                 * CuadroDialogo.InitialDirectory = @"D:\RESPALDO\SEMANARI\";
                 * if (CuadroDialogo.ShowDialog() == DialogResult.OK)
                 * {
                 *   oWord.ActiveDocument.SaveAs(CuadroDialogo.FileName);
                 *   oWord.ActiveDocument.Saved = true;
                 *   CuadroDialogo.Dispose();
                 *   CuadroDialogo = null;
                 * }*/
            }
            catch (Exception) { }
            finally
            {
                oWord.Visible = true;
            }
            return(0);
        }
Esempio n. 7
0
        public static int FileGeneration(Bitmap bitmap)
        {
            try
            {
                int returnval = 0;
                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);

                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.wdAlignParagraphCenter;
                    headerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
                    headerRange.Font.Size = 10;
                    headerRange.Text      = "SAMPLE HEADER NAME";
                }


                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 = bitmap.ToString();
                para1.Range.InsertParagraphAfter();


                object filename = @"E:\TestFile.docx";
                document.SaveAs2(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 !");
                return(returnval);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 8
0
        private void SaveDataToDoc(string data, string outPath)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            //app.ShowAnimation = false;
            app.Visible = false;
            object missing = System.Reflection.Missing.Value;

            string source = Path.Combine(Application.StartupPath, outPath);

            Microsoft.Office.Interop.Word.Document document = app.Documents.Add();
            //doc.Activate();
            Microsoft.Office.Interop.Word.Paragraph paragraph = document.Content.Paragraphs.Add();
            paragraph.Range.Text = data;
            paragraph.Range.InsertParagraphAfter();
            document.SaveAs2(source);
            document.Close();
            releaseObject(document);
            app.Quit();
            releaseObject(app);
        }
        private void testFichierWord()
        {
            Microsoft.Office.Interop.Word.Application msWord = new Microsoft.Office.Interop.Word.Application();
            msWord.Visible = true; // mettez cette variable à true si vous souhaitez visualiser les opérations.
            object missing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Document nvDoc;
            // Choisir le template
            // object templateName = @"proALPHA\proALPHA_Konzept.dot";
            object templateName = @"Test2.dotx";

            // Créer le document
            nvDoc = msWord.Documents.Add(ref templateName, ref missing, ref missing, ref missing);

            /*
             * HashSet<string> hash = new HashSet<string>();
             * foreach (Microsoft.Office.Interop.Word.FormField f in nvDoc.FormFields)
             * {
             *  hash.Add(f.Name);
             * }
             *
             * // Opérations
             * // Les champs de formulaire définis dans le modèle se nomment "Nom" et "Prenom".
             * object field = "Text1";
             * nvDoc.FormFields.get_Item(ref field).Result = "1";
             * field = "Text2";
             * nvDoc.FormFields.get_Item(ref field).Result = "2";
             */
            /*
             * // Le texte que je transfère
             * string monContenu = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl
             *                  {\f0\fswiss\fcharset0 Arial;}{\f1\fnil\fcharset0 Arial;}
             *                  {\f2\fmodern\fprq1\fcharset0 Courier;}}
             *                  {\colortbl ;\red0\green0\blue0;}
             *                  {\*\generator Msftedit 5.41.15.1503;}
             *                  \cf1\b\i\f2 Le texte que je transfère\cf0\b0\i0\f0}";
             * DataObject clipData = new DataObject(DataFormats.Rtf,monContenu);
             * Clipboard.SetDataObject(clipData,false);
             */
            /*
             * string monContenu = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl
             *                  {\f0\fswiss\fcharset0 Arial;}{\f1\fnil\fcharset0 Arial;}
             *                  {\f2\fmodern\fprq1\fcharset0 Courier;}}
             *                  {\colortbl ;\red0\green0\blue0;}
             *                  {\*\generator Msftedit 5.41.15.1503;}
             *                  \cf1\b\i\f2 Le texte que je transfère\cf0\b0\i0\f0}";
             * DataObject clipData = new DataObject(DataFormats.Rtf,monContenu);
             * Clipboard.SetDataObject(clipData,false);
             * msWord.Selection.Paste();
             */

            object field = "Text1";

            nvDoc.FormFields.get_Item(ref field).Result = "Checklist : ";

            Microsoft.Office.Interop.Word.Paragraph description = nvDoc.Content.Paragraphs.Add(ref missing);
            description.Range.Text = "Description";
            description.Range.InsertParagraphAfter();


            // Attribuer le nom
            object fileName = @"test.doc";

            // Sauver le document
            nvDoc.SaveAs(ref fileName, 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);
            // Fermer le document
            nvDoc.Close(ref missing, ref missing, ref missing);

            msWord.Quit(ref missing, ref missing, ref missing);
        }
Esempio n. 10
0
        /// <summary>
        /// Writes data contained in ADO.NET DataTable object to path stored in DocumentFilePath property.
        /// </summary>
        /// <param name="dt">DataTable object containing data to be imported.</param>
        /// <returns>True if output operation is successful. False if write fails.</returns>
        public bool WriteDataToDocument(DataTable dt)
        {
            bool   success = true;
            object missing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Application wordApp = null;
            Microsoft.Office.Interop.Word.Document    wordDoc = null;
            int numCols   = 0;
            int numRows   = 0;
            int tblRows   = 0;
            int curTblRow = 0;

            try
            {
                if (File.Exists(this.DocumentFilePath))
                {
                    if (_replaceExistingFile)
                    {
                        File.SetAttributes(this.DocumentFilePath, FileAttributes.Normal);
                        File.Delete(this.DocumentFilePath);
                    }
                    else
                    {
                        _msg.Length = 0;
                        _msg.Append("Word document file exists and ReplaceExistingFile set to False. Write to Word document has failed.");
                        throw new System.Exception(_msg.ToString());
                    }
                }

                numCols = dt.Columns.Count;
                numRows = dt.Rows.Count;
                tblRows = numRows + 1;

                wordApp         = new Microsoft.Office.Interop.Word.Application();
                wordApp.Visible = false;

                Microsoft.Office.Interop.Word.WdSaveFormat fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
                switch (this.WordOutputFormat)
                {
                case enWordOutputFormat.Word2007:
                    fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument;
                    break;

                case enWordOutputFormat.Word2003:
                    fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
                    break;

                case enWordOutputFormat.RTF:
                    fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF;
                    break;

                case enWordOutputFormat.PDF:
                    fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
                    break;

                default:
                    fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
                    break;
                }

                wordDoc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                wordDoc.Content.SetRange(0, 0);
                Microsoft.Office.Interop.Word.Paragraph para1 = wordDoc.Content.Paragraphs.Add(ref missing);
                Microsoft.Office.Interop.Word.Table     tbl   = wordDoc.Tables.Add(para1.Range, tblRows, numCols, ref missing, ref missing);

                curTblRow = 1;
                for (int c = 0; c < dt.Columns.Count; c++)
                {
                    tbl.Rows[curTblRow].Cells[c + 1].Range.Text = dt.Columns[c].ColumnName;
                }

                for (int r = 0; r < dt.Rows.Count; r++)
                {
                    curTblRow++;
                    for (int c = 0; c < dt.Columns.Count; c++)
                    {
                        tbl.Rows[curTblRow].Cells[c + 1].Range.Text = dt.Rows[r][c].ToString();
                    }
                }


                tbl.AllowAutoFit = true;
                tbl.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitWindow);
                wordDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
                wordDoc.PageSetup.PaperSize   = Microsoft.Office.Interop.Word.WdPaperSize.wdPaper11x17;

                wordDoc.SaveAs2(this.DocumentFilePath, fileFormat, 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);
                //wordDoc.Save();
                //wordDoc.Close(false);
                //wordApp.Quit(false);
                //((Microsoft.Office.Interop.Word._Document)wordDoc).Close(ref nullobject, ref nullobject, ref nullobject);
                //((Microsoft.Office.Interop.Word._Application)wordApp).Quit(ref nullobject, ref nullobject, ref nullobject);
                ((Microsoft.Office.Interop.Word._Document)wordDoc).Close(null, null, null);
                ((Microsoft.Office.Interop.Word._Application)wordApp).Quit(null, null, null);
            }
            catch (System.Exception ex)
            {
                success     = false;
                _msg.Length = 0;
                _msg.Append("Attempt to import DataTable into Word document failed.");
                _msg.Append(Environment.NewLine);
                _msg.Append(PFTextProcessor.FormatErrorMessage(ex));
                throw new System.Exception(_msg.ToString());
            }
            finally
            {
                if (wordApp != null)
                {
                    wordApp = null;
                }
            }

            return(success);
        }
        public static void testFichierWord(string titre, string desc, Panel panel, DataTable types)
        {
            Microsoft.Office.Interop.Word.Application msWord = new Microsoft.Office.Interop.Word.Application();
            msWord.Visible = false; // mettez cette variable à true si vous souhaitez visualiser les opérations.
            object missing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Document nvDoc;
            // Choisir le template
            // object templateName = @"proALPHA\proALPHA_Konzept.dot";
            object templateName = @"Test3.doc";

            // Créer le document
            nvDoc = msWord.Documents.Add(ref templateName, ref missing, ref missing, ref missing);

            object field = "Text1";

            nvDoc.FormFields.get_Item(ref field).Result = "Checklist : " + titre;

            Microsoft.Office.Interop.Word.Paragraph description = nvDoc.Content.Paragraphs.Add(ref missing);
            object style3 = "Schwache Hervorhebung";

            description.Range.set_Style(style3);
            description.Range.Font.Size = 12;
            description.Range.Text      = "Beschreibung : " + desc + Environment.NewLine;
            description.Range.InsertParagraphAfter();

            string titrePoint = string.Empty;
            string descPoint  = string.Empty;
            string typesPoint = string.Empty;


            Microsoft.Office.Interop.Word.Paragraph liste = nvDoc.Content.Paragraphs.Add(ref missing);
            object style5 = "Buchtitel";

            liste.Range.set_Style(style5);
            liste.Range.Font.Size = 13;
            liste.Range.Text      = "Punkte Liste : " + Environment.NewLine;
            liste.Range.InsertParagraphAfter();

            string IDPoint = string.Empty;

            foreach (Control control in panel.Controls)
            {
                if (control.GetType() == typeof(Panel) && control.Name.StartsWith(Constantes.panelPoint))
                {
                    typesPoint = string.Empty;
                    IDPoint    = Tools.returnID(control.Name);
                    DataRow row = types.Rows.Find(IDPoint);
                    foreach (Control point in control.Controls)
                    {
                        if (point.Name == Constantes.labelTitrePoint)
                        {
                            titrePoint = point.Text;
                        }
                        else if (point.Name == Constantes.labelDescriptionPoint)
                        {
                            descPoint = point.Text;
                        }
                        else if (point.Name.StartsWith(Constantes.pointEntwickler))
                        {
                            if ((bool)types.Rows.Find(IDPoint)[Constantes.entwickler])
                            {
                                if (typesPoint != string.Empty)
                                {
                                    typesPoint += " - ";
                                }
                                typesPoint += "Entwickler";
                            }
                        }
                        else if (point.Name.StartsWith(Constantes.pointBerater))
                        {
                            if ((bool)types.Rows.Find(IDPoint)[Constantes.berater])
                            {
                                if (typesPoint != string.Empty)
                                {
                                    typesPoint += " - ";
                                }
                                typesPoint += "Berater";
                            }
                        }
                        else if (point.Name.StartsWith(Constantes.pointTechnik))
                        {
                            if ((bool)types.Rows.Find(IDPoint)[Constantes.technik])
                            {
                                if (typesPoint != string.Empty)
                                {
                                    typesPoint += " - ";
                                }
                                typesPoint += "Technik";
                            }
                        }
                        else if (point.Name.StartsWith(Constantes.pointKunde))
                        {
                            if ((bool)types.Rows.Find(IDPoint)[Constantes.kunde])
                            {
                                if (typesPoint != string.Empty)
                                {
                                    typesPoint += " - ";
                                }
                                typesPoint += "Kunde";
                            }
                        }
                    }
                    Microsoft.Office.Interop.Word.Paragraph tPoint = nvDoc.Content.Paragraphs.Add(ref missing);
                    object style1 = "Intensive Hervorhebung";
                    tPoint.Range.set_Style(style1);
                    tPoint.Range.Font.Size = 14;
                    tPoint.Range.Text      = titrePoint;
                    tPoint.Range.InsertParagraphAfter();

                    Microsoft.Office.Interop.Word.Paragraph tUserPoint = nvDoc.Content.Paragraphs.Add(ref missing);
                    object style4 = "Intensives Zitat";
                    tUserPoint.Range.set_Style(style4);
                    tUserPoint.Range.Font.Size   = 10;
                    tUserPoint.Range.Font.Bold   = 0;
                    tUserPoint.Range.Font.Italic = 1;

                    tUserPoint.Range.Text = typesPoint;
                    tUserPoint.Range.InsertParagraphAfter();

                    Microsoft.Office.Interop.Word.Paragraph dPoint = nvDoc.Content.Paragraphs.Add(ref missing);
                    object style2 = "Hervorhebung";
                    dPoint.Range.set_Style(style2);
                    dPoint.Range.Font.Size = 11;
                    dPoint.Range.Text      = descPoint;
                    dPoint.Range.InsertParagraphAfter();
                }
            }

            // Attribuer le nom
            object fileName = @"test.doc";

            // Sauver le document
            nvDoc.SaveAs(ref fileName, 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);

            // Fermer le document
            // nvDoc.Close(ref missing,ref missing,ref missing);

            msWord.Documents.Open(ref fileName, 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);

            // msWord.Quit(ref missing,ref missing,ref missing);
        }
Esempio n. 12
0
        private void btnToWord_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Office.Interop.Word.Application winword =
                    new Microsoft.Office.Interop.Word.Application();

                winword.Visible = false;

                //Заголовок документа
                winword.Documents.Application.Caption = "CrimesAndIncidents";

                object missing = System.Reflection.Missing.Value;

                //Создание нового документа
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                //Добавление текста в документ
                document.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
                document.Content.SetRange(0, 0);

                //Добавление текста со стилем Заголовок 1
                Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
                //para1.Range.set_Style(styleHeading1);
                para1.Range.Font.Size = 14;
                para1.Range.Text      = "Преступления и происшествия за " +
                                        ((dpLeft.Text == "" && dpRight.Text == "") ? "все время" :
                                         ("период " +
                                          (dpLeft.Text == "" ? "" : "c " + dpLeft.Text) +
                                          (dpRight.Text == "" ? "" : " по " + dpRight.Text)));
                para1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                para1.Range.InsertParagraphAfter();
                para1.Range.InsertParagraphAfter();

                //Создание таблицы 5х5
                Microsoft.Office.Interop.Word.Table firstTable = document.Tables.Add(
                    para1.Range,
                    crimesDataGrid.Items.Count + 1, //число строк
                    crimesDataGrid.Columns.Count,   //число столбцов нужно динамически, после того как будет выбор столбцов
                    ref missing,
                    ref missing);

                firstTable.Range.Font.Size = 12;
                firstTable.Range.Font.Name = "Times New Roman";
                firstTable.Borders.Enable  = 1;

                for (int i = 0; i < firstTable.Rows.Count; i++)
                {
                    for (int j = 0; j < firstTable.Columns.Count; j++)
                    {
                        //Заголовок таблицы
                        if (i == 0)
                        {
                            firstTable.Rows[1].Cells[j + 1].Range.Text = j == 0 ? "№\nп/п" : crimesDataGrid.Columns[j].Header.ToString();

                            //Выравнивание текста в заголовках столбцов по центру
                            firstTable.Rows[i + 1].Cells[j + 1].VerticalAlignment =
                                Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            firstTable.Rows[i + 1].Cells[j + 1].Range.ParagraphFormat.Alignment =
                                Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        }
                        //Значения ячеек
                        else if (j == 0)
                        {
                            firstTable.Rows[i + 1].Cells[j + 1].Range.Text = i.ToString();
                        }
                    }

                    if (i != 0)
                    {
                        firstTable.Rows[i + 1].Cells[2].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).NumberCase;
                        firstTable.Rows[i + 1].Cells[3].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).Story;
                        firstTable.Rows[i + 1].Cells[4].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).DateCommit;
                        firstTable.Rows[i + 1].Cells[5].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).DateInstitution;
                        firstTable.Rows[i + 1].Cells[6].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).DateRegistration;
                        firstTable.Rows[i + 1].Cells[7].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).Damage;
                        firstTable.Rows[i + 1].Cells[8].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).PostAccomplice;
                        firstTable.Rows[i + 1].Cells[9].Range.Text  = (crimesDataGrid.Items[i - 1] as Crime).Accomplice;
                        firstTable.Rows[i + 1].Cells[10].Range.Text = (crimesDataGrid.Items[i - 1] as Crime).Clause;
                        firstTable.Rows[i + 1].Cells[11].Range.Text = (crimesDataGrid.Items[i - 1] as Crime).DateVerdict;
                        firstTable.Rows[i + 1].Cells[12].Range.Text = (crimesDataGrid.Items[i - 1] as Crime).Verdict;
                        firstTable.Rows[i + 1].Cells[13].Range.Text = (crimesDataGrid.Items[i - 1] as Crime).MilitaryUnit;
                    }
                }
                firstTable.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent);

                winword.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 13
0
        private void btnGenerateCV_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

            word.Documents.Add();
            word.Visible       = false;
            word.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
            Microsoft.Office.Interop.Word.Document doc = word.ActiveDocument;


            Microsoft.Office.Interop.Word.Paragraph paragraph = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "Kamal Ashraf";
            paragraph.Range.Font.Size = 22;
            paragraph.Range.Font.Bold = 1;
            paragraph.Range.Font.Name = "Times New Roman (Headings CS)";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraph.Range.InsertParagraphAfter();


            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "Gujrat, Pakistan";
            paragraph.Range.Font.Size = 12;
            paragraph.Range.Font.Bold = 0;
            paragraph.Range.Font.Name = "Times New Roman (Headings CS)";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph.Range.InsertParagraphAfter();



            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "CNIC:\t\t\t\t31001-1234567-1";
            paragraph.Range.Font.Size = 12;
            paragraph.Range.Font.Bold = 0;
            paragraph.Range.Font.Name = "Times New Roman (Headings CS)";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph.Range.InsertParagraphAfter();


            string textToFind = "CNIC:";

            Microsoft.Office.Interop.Word.Range range;
            Microsoft.Office.Interop.Word.Range textFormat;

            range = doc.Range();
            range.Find.Execute(textToFind);
            object start = range.Start;
            object end   = range.Start + textToFind.Length + 1;

            textFormat           = doc.Range(ref start, ref end);
            textFormat.Font.Bold = 1;


            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "Date of birth:\t\t\t12th November 1992";
            paragraph.Range.Font.Size = 12;
            paragraph.Range.Font.Bold = 0;
            paragraph.Range.Font.Name = "Times New Roman (Headings CS)";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph.Range.InsertParagraphAfter();

            textToFind = "Date of birth:";
            range      = doc.Range();
            range.Find.Execute(textToFind);
            start                = range.Start;
            end                  = range.Start + textToFind.Length + 1;
            textFormat           = doc.Range(ref start, ref end);
            textFormat.Font.Bold = 1;

            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "Email address:\t\t" + "*****@*****.**";
            paragraph.Range.Font.Size = 12;
            paragraph.Range.Font.Bold = 0;
            paragraph.Range.Font.Name = "Times New Roman (Headings CS)";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph.Range.InsertParagraphAfter();

            textToFind = "Email address:";
            range      = doc.Range();
            range.Find.Execute(textToFind);
            start                = range.Start;
            end                  = range.Start + textToFind.Length + 1;
            textFormat           = doc.Range(ref start, ref end);
            textFormat           = doc.Range(ref start, ref end);
            textFormat.Font.Bold = 1;

            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "Mobile number:\t\t+92-300-1234567";
            paragraph.Range.Font.Size = 12;
            paragraph.Range.Font.Bold = 0;
            paragraph.Range.Font.Name = "Times New Roman (Headings CS)";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph.Range.InsertParagraphAfter();

            textToFind = "Mobile number:";
            range      = doc.Range();
            range.Find.Execute(textToFind);
            start                = range.Start;
            end                  = range.Start + textToFind.Length + 1;
            textFormat           = doc.Range(ref start, ref end);
            textFormat           = doc.Range(ref start, ref end);
            textFormat.Font.Bold = 1;

            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "Landline number:\t\t+92-55-66777";
            paragraph.Range.Font.Size = 12;
            paragraph.Range.Font.Bold = 0;
            paragraph.Range.Font.Name = "Times New Roman (Headings CS)";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph.Range.InsertParagraphAfter();

            textToFind = "Landline number:";
            range      = doc.Range();
            range.Find.Execute(textToFind);
            start                = range.Start;
            end                  = range.Start + textToFind.Length + 1;
            textFormat           = doc.Range(ref start, ref end);
            textFormat           = doc.Range(ref start, ref end);
            textFormat.Font.Bold = 1;


            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "About me";
            paragraph.Range.Font.Size = 18;
            paragraph.Range.Font.Bold = 1;
            paragraph.Range.Font.Name = "Calibri";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraph.Shading.ForegroundPatternColor  = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;


            paragraph.Range.InsertParagraphAfter();

            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "I am able to handle multiple tasks on a daily basis. I use a creative approach to problem solve. I am a dependable person who is great at time management. I am always energetic and eager to learn new skills. I am flexible in my working hours, being able to work evenings and weekends. I am hardworking and always the last to leave the office in the evening.";
            paragraph.Range.Font.Size = 12;
            paragraph.Range.Font.Bold = 0;
            paragraph.Range.Font.Name = "Times New Roman (Headings CS)";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph.Shading.ForegroundPatternColor  = Microsoft.Office.Interop.Word.WdColor.wdColorWhite;
            paragraph.Range.InsertParagraphAfter();


            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "Qualification";
            paragraph.Range.Font.Size = 18;
            paragraph.Range.Font.Bold = 1;
            paragraph.Range.Font.Name = "Calibri";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraph.Shading.ForegroundPatternColor  = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
            paragraph.Range.InsertParagraphAfter();


            List <string> qualificationList = new List <string>();

            qualificationList.Add("MPhill: 3.0/4.0 CGPA");
            qualificationList.Add("MSc: 70% marks");
            qualificationList.Add("BSc: 65% marks");
            qualificationList.Add("Inter: 70% marks");
            qualificationList.Add("Matriculation: 75% marks");

            object oEndOfDoc = "\\endofdoc";

            Microsoft.Office.Interop.Word.Range wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            paragraph.Shading.ForegroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorWhite;


            paragraph = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph.Range.Font.Name = "Times New Roman (Headings CS)";

            paragraph.Range.ListFormat.ApplyBulletDefault();

            for (int i = 0; i < qualificationList.Count; i++)
            {
                string bulletItem = qualificationList[i];
                if (i < qualificationList.Count - 1)
                {
                    bulletItem = bulletItem + "\n";
                }
                paragraph.Range.Font.Bold = 0;
                paragraph.Range.InsertBefore(bulletItem);
            }


            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "Experience";
            paragraph.Range.Font.Size = 18;
            paragraph.Range.Font.Bold = 1;
            paragraph.Range.Font.Name = "Calibri";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraph.Shading.ForegroundPatternColor  = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
            paragraph.Range.InsertParagraphAfter();

            List <string> experienceList = new List <string>();

            experienceList.Add("Worked in Company A: 2014 to 2015");
            experienceList.Add("Worked in Company B: 2015 to 2016");
            experienceList.Add("Worked in Company C: 2016 to 2017");
            experienceList.Add("Worked in Company D: 2017 to 2018");
            experienceList.Add("Worked in Company E: 2018 to 2019");

            oEndOfDoc = "\\endofdoc";



            paragraph = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph.Range.Font.Name = "Times New Roman (Headings CS)";
            paragraph.Shading.ForegroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorWhite;

            paragraph.Range.ListFormat.ApplyBulletDefault();

            for (int i = 0; i < experienceList.Count; i++)
            {
                string bulletItem = experienceList[i];
                if (i < experienceList.Count - 1)
                {
                    bulletItem = bulletItem + "\n";
                }
                paragraph.Range.Font.Bold = 0;
                paragraph.Range.InsertBefore(bulletItem);
            }

            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "Interests";
            paragraph.Range.Font.Size = 18;
            paragraph.Range.Font.Bold = 1;
            paragraph.Range.Font.Name = "Calibri";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraph.Shading.ForegroundPatternColor  = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
            paragraph.Range.InsertParagraphAfter();

            paragraph                 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph.Range.Text      = "Playing video games and cricket";
            paragraph.Range.Font.Size = 12;
            paragraph.Range.Font.Bold = 0;
            paragraph.Range.Font.Name = "Calibri";
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraph.Shading.ForegroundPatternColor  = Microsoft.Office.Interop.Word.WdColor.wdColorWhite;
            paragraph.Range.InsertParagraphAfter();


            string imagePath = System.AppDomain.CurrentDomain.BaseDirectory + "../../../person.png";

            Microsoft.Office.Interop.Word.InlineShape inlineShape = doc.InlineShapes.AddPicture(imagePath, Type.Missing, Type.Missing, Type.Missing);
            Microsoft.Office.Interop.Word.Shape       shape       = inlineShape.ConvertToShape();
            shape.HeightRelative  = 10f;
            shape.WidthRelative   = 18f;
            shape.Left            = (float)Microsoft.Office.Interop.Word.WdShapePosition.wdShapeRight;
            shape.Top             = 40F;
            shape.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;


            foreach (Microsoft.Office.Interop.Word.Section wordSection in doc.Sections)
            {
                Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                footerRange.Collapse(Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd);

                footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages);
                Microsoft.Office.Interop.Word.Paragraph p4 = footerRange.Paragraphs.Add();
                p4.Range.Text = " of ";
                footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                Microsoft.Office.Interop.Word.Paragraph p1 = footerRange.Paragraphs.Add();
                p1.Range.Text = "Page ";
                footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
            }



            Microsoft.Win32.SaveFileDialog dialogBox = new Microsoft.Win32.SaveFileDialog();
            dialogBox.Title      = "Choose destination to save file";
            dialogBox.DefaultExt = ".pdf";
            dialogBox.Filter     = "Word documents (.docx)|*.docx|PDF documents (.pdf)|*.pdf";
            bool?result = dialogBox.ShowDialog();

            if (result == true)
            {
                string fileName = dialogBox.FileName;
                if (fileName.EndsWith(".docx"))
                {
                    doc.SaveAs(fileName);
                }
                else if (fileName.EndsWith(".pdf"))
                {
                    doc.ExportAsFixedFormat(fileName, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
                }
                MessageBox.Show("File \"" + fileName + "\"" + " saved.", "Success");
            }

            doc.Close(0);
            word.Quit();
            Marshal.ReleaseComObject(doc);
        }
Esempio n. 14
0
        private void Print()
        {
            AnalyzeView analyzeView = new AnalyzeView();

            analyzeView.Show();

            return;

            CalendarView calendar = new CalendarView();

            calendar.ViewModel.OKClicked += (s, e) =>
            {
                var data = e.EventData;

                var startDate = data.Item1;
                var endDate   = data.Item2;

                if (startDate > endDate)
                {
                    var temp = startDate;
                    startDate = endDate;
                    endDate   = temp;
                }

                var result = _database.GetPeriodListAccount(DateHelper.ToStringDate(startDate), DateHelper.ToStringDate(endDate));
                try
                {
                    var modelList = JsonConvert.DeserializeObject <List <DailyModel> >(result);
                    modelList.Sort((DailyModel x, DailyModel y) => x.Date.CompareTo(y.Date));

                    if (modelList != null && modelList.Count > 0)
                    {
                        Microsoft.Office.Interop.Word.Application word     = new Microsoft.Office.Interop.Word.Application();
                        Microsoft.Office.Interop.Word.Document    document = new Microsoft.Office.Interop.Word.Document();

                        Object oMissing = System.Reflection.Missing.Value;
                        Object oFalse   = false;

                        Microsoft.Office.Interop.Word.Paragraph paragraph = document.Content.Paragraphs.Add(ref oMissing);
                        paragraph.Range.Font.Size = 15;

                        object start     = 0;
                        object end       = 0;
                        object oEndOfDoc = "\\endofdoc";
                        Microsoft.Office.Interop.Word.Range tableLocation = document.Bookmarks.get_Item(ref oEndOfDoc).Range;
                        var table = document.Content.Tables.Add(tableLocation, modelList.Count, 4);
                        table.Range.Font.Size          = 15;
                        table.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        table.AllowAutoFit             = true;

                        int row = 1;
                        foreach (var model in modelList)
                        {
                            table.Cell(row, 1).Range.Text = model.Date;
                            table.Cell(row, 2).Range.Text = model.Type.ToString();
                            table.Cell(row, 3).Range.Text = model.Name;

                            if (model.Type == ItemType.Outgo || model.Type == ItemType.Kakao ||
                                model.Type == ItemType.Samsung || model.Type == ItemType.Hana ||
                                model.Type == ItemType.Hyundai || model.Type == ItemType.Cash)
                            {
                                table.Cell(row, 4).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;
                            }
                            else
                            {
                                table.Cell(row, 4).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlue;
                            }

                            table.Cell(row, 4).Range.Text = "\\ " + string.Format("{0:###,###,###,###,###,###,###}", model.Amount);

                            row++;
                        }

                        table.Columns[1].AutoFit();
                        Single width1 = table.Columns[1].Width;
                        table.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent); // fill page width
                        table.Columns[1].SetWidth(width1, Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustFirstColumn);

                        table.Columns[2].AutoFit();
                        Single width2 = table.Columns[2].Width;
                        table.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent); // fill page width
                        table.Columns[2].SetWidth(width2, Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustFirstColumn);

                        table.Columns[3].AutoFit();
                        Single width3 = table.Columns[3].Width;
                        table.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent); // fill page width
                        table.Columns[3].SetWidth(width3, Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustFirstColumn);

                        table.Columns[4].AutoFit();
                        Single width4 = table.Columns[4].Width;
                        table.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent); // fill page width
                        table.Columns[4].SetWidth(width4, Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustFirstColumn);

                        table.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter;

                        document.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;

                        Object fileName = Directory.GetCurrentDirectory() + "\\" + "Report_" + DateHelper.ToStringDate(startDate) + "_" + DateHelper.ToStringDate(endDate) + ".doc";

                        try
                        {
                            document.SaveAs(ref fileName);

                            System.Diagnostics.Process.Start(fileName.ToString());

                            if (word.ActivePrinter != null || word.ActivePrinter != "")
                            {
                                document.PrintOut(ref oFalse, ref oMissing, ref oMissing, ref oMissing,
                                                  ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oFalse,
                                                  ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                            }

                            document.Close();
                            word.Quit();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("오류가 발생했습니다. 다시 시도 해 주세요.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            };
            calendar.ViewModel.Closing += (s, e) =>
            {
                calendar.Close();
            };
            calendar.ViewModel.SelectedStartDate = DateHelper.GetMondayOfWeek(_selectedDate);
            calendar.ViewModel.SelectedEndDate   = DateHelper.GetSundayOfWeek(_selectedDate);
            calendar.ShowDialog();
        }
Esempio n. 15
0
        private void WriteUp_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine(ListViewHeaderSet);
            IntegerConverter integerConverter = new IntegerConverter();

            //WE GET THE SELECTED ITEM LISTVIEW
            Contracts selected = (Contracts)lvUsers.SelectedItem;
            string    content  = System.IO.File.ReadAllText($@"C:\Users\gnpie\OneDrive\Escritorio\proyectos\Portal Ciudadano\{ListViewHeaderSet.ToString()}\{selected.Name}.txt");

            //ON THE RELATED .TXT WE SEEK THE VARIABLES CONTAINDE ON IT
            List <int> listOfLegalDocumentVariablesIndices = new List <int>();
            bool       variableFinded = true;
            int        lastsearching  = 0;

            while (variableFinded == true)
            {
                int startIndex = content.IndexOf("${", lastsearching);
                if (startIndex == -1)
                {
                    variableFinded = false;
                }
                if (startIndex != -1)
                {
                    listOfLegalDocumentVariablesIndices.Add(startIndex + 2);
                }
                int endIndex = content.IndexOf("}", lastsearching);
                if (endIndex != -1)
                {
                    listOfLegalDocumentVariablesIndices.Add(endIndex);
                }
                lastsearching = endIndex + 1;
            }

            int           iterator = 0;
            List <string> listOfLegalDocumentVariablesNames = new List <string>();

            while (iterator <= listOfLegalDocumentVariablesIndices.Count - 2)
            {
                int    length = listOfLegalDocumentVariablesIndices[iterator + 1] - listOfLegalDocumentVariablesIndices[iterator];
                string piece  = content.Substring(listOfLegalDocumentVariablesIndices[iterator], length);
                listOfLegalDocumentVariablesNames.Add(piece);
                iterator = iterator + 2;
            }

            // INITIALIZATION OF WORD DOCUMENT
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            word.Documents.Add();
            word.Visible       = true;
            word.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
            Microsoft.Office.Interop.Word.Document doc = word.ActiveDocument;

            //WE FIND THE SELECTED CASE DATA

            Client selectedClient = new Client();

            foreach (Client item in AllClients)
            {
                if (item.clients_name == lbUsers.Text)
                {
                    selectedClient = item;
                }
            }

            //WE STORE THE INPUTS (TEXTBOXES) CONTENT, FOR THE DOCUMENT CONSTRUCTOR


            int maxLoops = VisualTreeHelper.GetChildrenCount(StackLayoutMap);
            Dictionary <string, string> labelsAndTextBoxesDict = new Dictionary <string, string>();

            for (int i = 0; i < maxLoops; i = i + 2)
            {
                string xamlLabelEle = VisualTreeHelper.GetChild(StackLayoutMap, i).ToString();
                //ver lector de xml xdoc
                string xamlTextBoxEle = "";
                if (i == maxLoops - 1)
                {
                    xamlTextBoxEle = VisualTreeHelper.GetChild(StackLayoutMap, i).ToString();
                }
                else
                {
                    xamlTextBoxEle = VisualTreeHelper.GetChild(StackLayoutMap, i + 1).ToString();
                }
                int startOnTextBox = xamlTextBoxEle.IndexOf("TextBox: ") + 9;
                int startOnLabel   = xamlLabelEle.IndexOf("Label: ") + 7;

                string textPropertiOfXamlElementTextBox  = xamlTextBoxEle.Substring(startOnTextBox); //HERE WE GET THE CONTENT OF TEXTBOX, WITH A TRICK
                string contentPropertiOfXamlElementLabel = xamlLabelEle.Substring(startOnLabel);

                labelsAndTextBoxesDict.Add(contentPropertiOfXamlElementLabel, textPropertiOfXamlElementTextBox);
            }

            // SECTIONS VARIABLES

            string rut = selectedClient.clients_rut;

            string[] rutArr                 = rut.Split('-');
            string   verifyingDigit         = integerConverter.Convert(Convert.ToInt64(rutArr[1]));
            string   theRestOFTheRut        = rutArr[0].Replace(".", "");
            long     theRestOFTheRutInteger = Convert.ToInt64(theRestOFTheRut);
            string   theRestOFTheRutOnWords = integerConverter.Convert(theRestOFTheRutInteger);
            string   stringifiedRut         = theRestOFTheRutOnWords + " guion " + verifyingDigit;

            string introduction  = $"EN SANTIAGO, REPÚBLICA DE CHILE, a {integerConverter.Convert(DateTime.Today.Day)} de {DateTime.Now.ToString("MMMM")} del año {integerConverter.Convert(DateTime.Today.Year)}, ante mí, R. ALFREDO MARTÍN ILLANES, abogado, Notario Púbico Titular de la Décimo Quinta Notaria de Santiago, con oficio en calle Mardoqueo Fernández doscientos uno, oficinas ciento uno y ciento dos, comuna de Providencia, comparece: ";
            string comparecencia = $"{selectedClient.clients_name}, {selectedClient.clients_nationality}, {selectedClient.clients_civilStatus}, {selectedClient.clients_job}, cédula nacional de identidad número {stringifiedRut}";
            string prefacio      = @" el compareciente mayor de edad, quien me acredita su identidad con la cédula personal antes citada y expone: ";

            //SECTION 1.a
            Microsoft.Office.Interop.Word.Paragraph paragraph1A = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph1A.Range.Text      = (selected.Name).ToUpper();
            paragraph1A.Range.Font.Size = 14;
            paragraph1A.Range.Font.Bold = 1;
            paragraph1A.Range.Font.Name = "Helvetica";
            paragraph1A.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraph1A.Range.InsertParagraphAfter();
            //SECTION 1.b
            Microsoft.Office.Interop.Word.Paragraph paragraph1B = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph1B.Range.Text      = selectedClient.clients_name.ToUpper();
            paragraph1B.Range.Font.Size = 14;
            paragraph1B.Range.Font.Bold = 1;
            paragraph1B.Range.Font.Name = "Helvetica";
            paragraph1B.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraph1B.Range.InsertParagraphAfter();
            //SECTION 1.c
            Microsoft.Office.Interop.Word.Paragraph paragraph1C = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph1C.Range.Text      = "A";
            paragraph1C.Range.Font.Size = 14;
            paragraph1C.Range.Font.Bold = 1;
            paragraph1C.Range.Font.Name = "Helvetica";
            paragraph1C.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraph1C.Range.InsertParagraphAfter();
            //SECTION 1.d
            Microsoft.Office.Interop.Word.Paragraph paragraph1D = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph1D.Range.Text      = "MEMIN";
            paragraph1D.Range.Font.Size = 14;
            paragraph1D.Range.Font.Bold = 1;
            paragraph1D.Range.Font.Name = "Helvetica";
            paragraph1D.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraph1D.Range.InsertParagraphAfter();

            //SECTION 2
            Microsoft.Office.Interop.Word.Paragraph paragraph2 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph2.Range.Text      = introduction + comparecencia + prefacio;
            paragraph2.Range.Font.Size = 12;
            paragraph2.Range.Font.Bold = 0;
            paragraph2.Range.Font.Name = "Helvetica";
            paragraph2.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
            //paragraph.Range.ParagraphFormat.LineSpacing = (float) Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpace1pt5;
            paragraph2.Range.InsertParagraphAfter();
            //SECTION 3
            Microsoft.Office.Interop.Word.Paragraph paragraph3 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);

            //============================================================================================================================


            foreach (KeyValuePair <string, string> entry in labelsAndTextBoxesDict)
            {
                if (content.Contains(entry.Key))
                {
                    int a;
                    if (Int32.TryParse(entry.Value, out a))
                    {
                        IntegerConverter intConverter = new IntegerConverter();
                        content = content.Replace("${" + entry.Key + "}", intConverter.Convert(Int64.Parse(entry.Value)));
                    }
                    else
                    {
                        content = content.Replace("${" + entry.Key + "}", entry.Value);
                    }
                }
            }

            /*string modifiedContent = content.Replace("${ANTECEDENTES}", "");
             * string modifiedContent2 = modifiedContent.Replace("${FOJAS}", "");
             * string modifiedContent3 = modifiedContent2.Replace("${NUMERO}", "");
             * string modifiedContent4 = modifiedContent3.Replace("${AÑO}", "");
             * string modifiedContent5 = modifiedContent4.Replace("${CIRCUNSCRIPCION}", "");
             * string modifiedContent6 = modifiedContent5.Replace("${PRECIO}", "");*/
            paragraph3.Range.Text      = content;
            paragraph3.Range.Font.Size = 12;
            paragraph3.Range.Font.Bold = 0;
            paragraph3.Range.Font.Name = "Helvetica";
            paragraph3.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
            //paragraph.Range.ParagraphFormat.LineSpacing = (float)Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceDouble;
            paragraph3.Range.InsertParagraphAfter();

            //SIGN SECTION
            Microsoft.Office.Interop.Word.Paragraph sign1 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph1B.Range.Text      = selectedClient.clients_name.ToUpper();
            paragraph1B.Range.Font.Size = 14;
            paragraph1B.Range.Font.Bold = 1;
            paragraph1B.Range.Font.Name = "Helvetica";
            paragraph1B.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph1B.Range.InsertParagraphAfter();
            Microsoft.Office.Interop.Word.Paragraph rut1 = doc.Content.Paragraphs.Add(System.Reflection.Missing.Value);
            paragraph1B.Range.Text      = selectedClient.clients_rut;
            paragraph1B.Range.Font.Size = 14;
            paragraph1B.Range.Font.Bold = 1;
            paragraph1B.Range.Font.Name = "Helvetica";
            paragraph1B.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph1B.Range.InsertParagraphAfter();
        }
Esempio n. 16
0
        public static void ExportWordByMicrosoftOfficeInteropWord(string databaseName, List <TableDto> tables)
        {
            string docTitle  = "数据库名:" + databaseName;
            object template  = System.Reflection.Missing.Value;
            object oEndOfDoc = @"\endofdoc"; // \endofdoc是预定义的bookmark

            // TODO 依赖冲突,所以用了全类名
            Microsoft.Office.Interop.Word._Application application = new Microsoft.Office.Interop.Word.Application();
            application.Visible = false;
            Microsoft.Office.Interop.Word._Document document = application.Documents.Add(ref template, ref template, ref template, ref template);
            application.ActiveWindow.View.Type     = Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;
            application.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;
            application.ActiveWindow.ActivePane.Selection.InsertAfter("DBCHM https://gitee.com/lztkdr/DBCHM");
            application.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
            application.ActiveWindow.View.SeekView          = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;

            Microsoft.Office.Interop.Word.Paragraph paragraph = document.Content.Paragraphs.Add(ref template);
            paragraph.Range.Text      = docTitle;
            paragraph.Range.Font.Bold = 1;
            paragraph.Range.Font.Name = "宋体";
            paragraph.Range.Font.Size = 12f;
            paragraph.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraph.Format.SpaceAfter = 5f;
            paragraph.OutlineLevel      = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevel1;
            paragraph.Range.InsertParagraphAfter();

            // TODO 遍历数据库表集合
            foreach (var table in tables)
            {
                string docTableName = table.TableName + " " + (!string.IsNullOrWhiteSpace(table.Comment) ? table.Comment : "");
                // TODO 一级标题
                object oRng = document.Bookmarks[oEndOfDoc].Range;
                Microsoft.Office.Interop.Word.Paragraph paragraph2 = document.Content.Paragraphs.Add(ref oRng);
                paragraph2.Range.Text      = docTableName;
                paragraph2.Range.Font.Bold = 1;
                paragraph2.Range.Font.Name = "宋体";
                paragraph2.Range.Font.Size = 10f;
                paragraph2.OutlineLevel    = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevel2;
                paragraph2.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                paragraph2.Format.SpaceBefore = 15f;
                paragraph2.Format.SpaceAfter  = 5f;
                paragraph2.Range.InsertParagraphAfter();

                // TODO 遍历数据库表字段集合
                // TODO 创建表格
                Microsoft.Office.Interop.Word.Range range  = document.Bookmarks[oEndOfDoc].Range;
                Microsoft.Office.Interop.Word.Table table2 = document.Tables.Add(range, table.Columns.Count + 1, 10, ref template, ref template);
                table2.Range.Font.Name        = "宋体";
                table2.Range.Font.Bold        = 0;
                table2.Range.Font.Size        = 9f;
                table2.Borders.Enable         = 1;
                table2.Rows.Height            = 10f;
                table2.AllowAutoFit           = true;
                table2.Cell(1, 1).Range.Text  = "序号";
                table2.Cell(1, 2).Range.Text  = "列名";
                table2.Cell(1, 3).Range.Text  = "数据类型";
                table2.Cell(1, 4).Range.Text  = "长度";
                table2.Cell(1, 5).Range.Text  = "小数位";
                table2.Cell(1, 6).Range.Text  = "主键";
                table2.Cell(1, 7).Range.Text  = "自增";
                table2.Cell(1, 8).Range.Text  = "允许空";
                table2.Cell(1, 9).Range.Text  = "默认值";
                table2.Cell(1, 10).Range.Text = "列说明";
                // TODO 分别设置word文档中表格的列宽

                int j = 0;
                foreach (var column in table.Columns)
                {
                    table2.Cell(j + 2, 1).Range.Text  = column.ColumnOrder;
                    table2.Cell(j + 2, 2).Range.Text  = column.ColumnName;
                    table2.Cell(j + 2, 3).Range.Text  = column.ColumnTypeName;
                    table2.Cell(j + 2, 4).Range.Text  = column.Length;
                    table2.Cell(j + 2, 5).Range.Text  = column.Scale;
                    table2.Cell(j + 2, 6).Range.Text  = column.IsPK;
                    table2.Cell(j + 2, 7).Range.Text  = column.IsIdentity;
                    table2.Cell(j + 2, 8).Range.Text  = column.CanNull;
                    table2.Cell(j + 2, 9).Range.Text  = column.DefaultVal;
                    table2.Cell(j + 2, 10).Range.Text = column.Comment;
                    j++;
                }
            }

            application.Visible = true;
            document.Activate();
        }
Esempio n. 17
0
        void PrintFormatReceipt()
        {
            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


                //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);

                document.Sections.PageSetup.TopMargin   = 30.0f;
                document.Sections.PageSetup.RightMargin = 30.0f;
                document.Sections.PageSetup.LeftMargin  = 30.0f;
                //document.SpellingChecked = true;
                //document.DisableFeatures = true;
                document.ShowSpellingErrors    = false;
                document.ShowGrammaticalErrors = false;
                //document.Sections[0].PageSetup.Orientation = PageOrientation.Landscape;

                //adding text to document
                document.Content.SetRange(0, 0);

                //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.Font.Size  = 14F;
                para1.Range.Font.Name  = "Arial Black";
                para1.Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlueGray;
                para1.Range.Text       = Company;
                para1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                para1.Range.InsertParagraphAfter();

                Microsoft.Office.Interop.Word.Table firstTable1 = document.Tables.Add(para1.Range, 6, 4, ref missing, ref missing);
                firstTable1.Borders.Enable  = 0;
                firstTable1.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly;
                //firstTable1.Rows.SetHeight(0.1f,Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAuto);

                firstTable1.Columns[1].Width = 65f;
                firstTable1.Columns[2].Width = 270f;
                firstTable1.Columns[3].Width = 55f;
                firstTable1.Columns[4].Width = 150f;

                //foreach (Microsoft.Office.Interop.Word.Column col in firstTable1.Columns)


                AddToCell(firstTable1, 1, 1, 9F, 1, "Address:");
                AddToCell(firstTable1, 1, 2, 9F, 0, Address);
                AddToCell(firstTable1, 1, 3, 9F, 1, "NTN:");
                AddToCell(firstTable1, 1, 4, 9F, 0, NTN);
                AddToCell(firstTable1, 2, 1, 9F, 1, "Mobile:");
                AddToCell(firstTable1, 2, 2, 9F, 0, Phone);
                AddToCell(firstTable1, 2, 3, 9F, 1, "STN:");
                AddToCell(firstTable1, 2, 4, 9F, 0, STN);
                AddToCell(firstTable1, 3, 1, 7F, 0, " ");
                AddToCell(firstTable1, 4, 1, 9F, 1, "Customer:");
                AddToCell(firstTable1, 4, 2, 9F, 0, cname.SelectedItem.ToString());
                AddToCell(firstTable1, 4, 3, 9F, 1, "Date:");
                AddToCell(firstTable1, 4, 4, 9F, 0, FrmDate.Value.ToShortDateString());
                AddToCell(firstTable1, 5, 1, 9F, 1, "Address:");
                AddToCell(firstTable1, 5, 2, 9F, 0, CAddress.Text);
                AddToCell(firstTable1, 5, 3, 9F, 1, "CNIC:");
                if (printcnic.Checked)
                {
                    if (cnic.SelectedItem == null)
                    {
                        cnic.SelectedIndex = 0;
                    }
                    AddToCell(firstTable1, 5, 4, 10F, 0, cnic.SelectedItem.ToString());
                }
                AddToCell(firstTable1, 6, 1, 9F, 1, "Status:");
                AddToCell(firstTable1, 6, 2, 9F, 0, Status.Text);
                AddToCell(firstTable1, 6, 3, 9F, 1, "Invoice:");
                AddToCell(firstTable1, 6, 4, 9F, 0, Invoice.Text);
                //para1.Range.InsertBreak(ref missing);

                Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
                para2.Range.Text = " ";
                para2.Range.InsertParagraphAfter();

                Microsoft.Office.Interop.Word.Table firstTable = document.Tables.Add(para2.Range, listView1.Items.Count + 2, 9, ref missing, ref missing);
                firstTable.Borders.Enable   = 0;
                firstTable.Columns[1].Width = 25f;
                firstTable.Columns[2].Width = 118f;
                firstTable.Columns[3].Width = 65f;
                firstTable.Columns[4].Width = 55f;
                firstTable.Columns[5].Width = 55f;
                firstTable.Columns[6].Width = 55f;
                firstTable.Columns[7].Width = 55f;
                firstTable.Columns[8].Width = 65f;
                firstTable.Columns[9].Width = 58f;


                firstTable.Rows[1].Cells.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorGray25;
                firstTable.Rows[1].Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                firstTable.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAuto;
                firstTable.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

                AddToCell(firstTable, 1, 1, 9f, 1, "Sr.");
                AddToCell(firstTable, 1, 2, 9f, 1, "Product");
                AddToCell(firstTable, 1, 3, 9f, 1, "Pack");
                AddToCell(firstTable, 1, 4, 9f, 1, "R.Pr");
                AddToCell(firstTable, 1, 5, 9f, 1, "Qty.");
                AddToCell(firstTable, 1, 6, 9f, 1, "T.Pr");
                AddToCell(firstTable, 1, 7, 9f, 1, "T.V(I.S)");
                AddToCell(firstTable, 1, 8, 9f, 1, "S.T@" + SaleTax.ToString() + "%");
                AddToCell(firstTable, 1, 9, 9f, 1, "S.Tax");

                int count   = 1;
                int rowindx = 2;
                foreach (ListViewItem item in listView1.Items)
                {
                    //for (int j = 1; j <= 9; j++)
                    //foreach (Microsoft.Office.Interop.Word.Cell cell in firstTable.Rows[count+1].Cells)
                    {
                        AddToCell(firstTable, rowindx, 1, 8.5f, 0, count.ToString());
                        AddToCell(firstTable, rowindx, 2, 8.5f, 0, item.SubItems[0].Text);
                        AddToCell(firstTable, rowindx, 3, 8.5f, 0, item.SubItems[1].Text);
                        AddToCell(firstTable, rowindx, 4, 8.5f, 0, item.SubItems[2].Text);
                        AddToCell(firstTable, rowindx, 5, 8.5f, 0, item.SubItems[3].Text);
                        AddToCell(firstTable, rowindx, 6, 8.5f, 0, item.SubItems[4].Text);
                        AddToCell(firstTable, rowindx, 7, 8.5f, 0, item.SubItems[5].Text);
                        AddToCell(firstTable, rowindx, 8, 8.5f, 0, item.SubItems[6].Text);
                        AddToCell(firstTable, rowindx, 9, 8.5f, 0, item.SubItems[7].Text);
                        count   += 1;
                        rowindx += 1;
                    }
                }

                firstTable.Rows[rowindx].Cells[5].Borders.Enable = 1;
                firstTable.Rows[rowindx].Cells[7].Borders.Enable = 1;
                firstTable.Rows[rowindx].Cells[9].Borders.Enable = 1;
                //firstTable.Rows[rowindx].Borders.JoinBorders = false;
                //firstTable.Rows[rowindx].Cells[5].Range.Font.Italic = 1;
                //firstTable.Rows[rowindx].Cells[7].Range.Font.Italic = 1;
                //firstTable.Rows[rowindx].Cells[9].Range.Font.Italic = 1;
                //firstTable.Rows[rowindx].Cells[5].Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorGray25;
                //firstTable.Rows[rowindx].Cells[7].Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorGray25;
                //firstTable.Rows[rowindx].Cells[9].Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorGray25;
                rowindx += 1;
                AddToCell(firstTable, rowindx, 4, 9f, 1, "Total:");
                AddToCell(firstTable, rowindx, 5, 8.5f, 1, Qty.Text);
                AddToCell(firstTable, rowindx, 7, 8.5f, 1, GrandTotal.Text);
                AddToCell(firstTable, rowindx, 9, 8.5f, 1, GrandTax.Text);

                Microsoft.Office.Interop.Word.Paragraph para3 = document.Content.Paragraphs.Add(ref missing);
                para3.Range.Text = " ";
                para3.Range.InsertParagraphAfter();

                Microsoft.Office.Interop.Word.Table firstTable2 = document.Tables.Add(para2.Range, 4, 3, ref missing, ref missing);
                firstTable2.Borders.Enable = 0;
                firstTable2.Rows[1].Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                firstTable2.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAuto;
                firstTable2.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                firstTable2.Columns[1].Width = 310f;
                firstTable2.Columns[2].Width = 125f;
                firstTable2.Columns[3].Width = 140;

                AddToCell(firstTable2, 1, 2, 10f, 1, "Sales Tax Inc.");
                AddToCell(firstTable2, 1, 3, 10f, 0, GrandTax.Text);
                AddToCell(firstTable2, 2, 2, 10f, 1, "Payable Amount.");
                AddToCell(firstTable2, 2, 3, 10f, 0, GrandTotal.Text);
                if (unpaid.Text == "")
                {
                    unpaid.Text = "0";
                }
                AddToCell(firstTable2, 3, 2, 10f, 1, "Prev. Bill.");
                AddToCell(firstTable2, 3, 3, 10f, 0, unpaid.Text);
                AddToCell(firstTable2, 4, 1, 10f, 1, "\tCustomer Sig.");
                AddToCell(firstTable2, 4, 2, 10f, 1, "Net Payable.");
                double NetPayable = GetDecimal(GrandTotal.Text) + GetDecimal(unpaid.Text);
                AddToCell(firstTable2, 4, 3, 10f, 0, NetPayable.ToString());

                Microsoft.Office.Interop.Word.Paragraph para4 = document.Content.Paragraphs.Add(ref missing);
                para4.Range.Text = " ";
                para4.Range.InsertParagraphAfter();

                Microsoft.Office.Interop.Word.Table firstTable3 = document.Tables.Add(para2.Range, 3, 2, ref missing, ref missing);
                firstTable2.Borders.Enable = 0;
                firstTable3.Rows[1].Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                firstTable3.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly;
                firstTable3.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                //firstTable3.Range.Font.Size = 10.5f;
                firstTable3.Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlueGray;
                firstTable3.Columns[1].Width = 40f;
                firstTable3.Columns[2].Width = 550f;
                AddToCell(firstTable3, 1, 1, 8.5f, 1, "Note:");
                AddToCell(firstTable3, 2, 2, 8.5f, 0, "No Expiry Claim will be Compensated.");
                AddToCell(firstTable3, 3, 2, 8.5f, 0, "Distribution is not responsible for any personal matter between Sales Staff and Customer.");


                //Save the document
                string dir = Application.StartupPath + "/" + FrmDate.Value.ToLongDateString();
                string dt  = dir + "/" + Invoice.Text + ".doc";

                DirectoryInfo di = new DirectoryInfo(dir);
                if (!di.Exists)
                {
                    di.Create();
                }
                object filename = dt;
                document.SaveAs(ref filename);
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;
                object readOnly  = true;
                object isVisible = true;
                //object missing1 = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Application wrd = new Microsoft.Office.Interop.Word.Application {
                    Visible = true
                };
                Microsoft.Office.Interop.Word.Document doc = wrd.Documents.Open(filename, ReadOnly: readOnly, Visible: isVisible);
                //MessageBox.Show("Document created successfully !");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }