예제 #1
0
        public void CreateDocument()
        {
            //Create New Word
            Document doc = new Document();

            //Add Section
            Spire.Doc.Section section = doc.AddSection();

            //Add Paragraph

            Spire.Doc.Documents.Paragraph Para = section.AddParagraph();

            //Append Text

            Para.AppendText("Hello! "

                            + "I was created by Spire.Doc for WPF, it's a professional .NET Word component "

                            + "which enables developers to perform a large range of tasks on Word document (such as create, open, write, edit, save and convert "

                            + "Word document) without installing Microsoft Office and any other third-party tools on system.");

            //Save and launch
            doc.SaveToFile("MyWord.docx", FileFormat.Docx);

            System.Diagnostics.Process.Start("MyWord.docx");
        }
예제 #2
0
        private void AddHeaderTitle(Spire.Doc.Section section)
        {
            Spire.Doc.Documents.Paragraph para1 = section.AddParagraph();
            para1.AppendText("TRƯỜNG ĐẠI HỌC SPKT TP.HCM").CharacterFormat.Bold = true;
            Spire.Doc.Tab tab1 = para1.Format.Tabs.AddTab(639);
            tab1.TabLeader = TabLeader.NoLeader;
            para1.AppendText("\tNgày in: 14/04/2021\n");

            Spire.Doc.Documents.Paragraph para2 = section.AddParagraph();
            Spire.Doc.Tab tab2 = para1.Format.Tabs.AddTab(36);
            para1.AppendText("\tPHÒNG ĐÀO TẠO\t").CharacterFormat.Bold = true;
            tab2           = para1.Format.Tabs.AddTab(693);
            tab2.TabLeader = TabLeader.NoLeader;
            para1.AppendText("\t Trang: 1\n");

            Spire.Doc.Documents.Paragraph para3 = section.AddParagraph();
            para3.AppendText("DANH SÁCH LỚP\n").CharacterFormat.Bold = true;
            para3.AppendText("\nHỌC KỲ: HK02 - NĂM HỌC 2020 - 2021\n").CharacterFormat.Bold = true;
            para3.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;

            Spire.Doc.Documents.Paragraph para4 = section.AddParagraph();
            para4.AppendText("Môn học/Nhóm:\t");
            Spire.Doc.Tab tab4 = para4.Format.Tabs.AddTab(261);
            tab4.TabLeader = TabLeader.NoLeader;
            para4.AppendText("Windows Programming (2+1) - 01CLC\t").CharacterFormat.Bold = true;
            tab4           = para4.Format.Tabs.AddTab(639);
            tab4.TabLeader = TabLeader.NoLeader;
            para4.AppendText("Số tín chỉ: 3\n");
            para4.AppendText("\nLớp học phần:\t");
            para4.AppendText("202WINPR230579E_01CLC\n").CharacterFormat.Bold = true;
            para4.AppendText("\nCBGD:\t");
            para4.AppendText("Lê Vĩnh Thịnh (0132)\n").CharacterFormat.Bold = true;
            para4.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left;
        }
예제 #3
0
        private void ExprtWord(object sender, RoutedEventArgs e)
        {
            //initial data source
            listStu      = exportStu.getStuData();
            dataRowCount = listStu.Count + 1;
            string path;

            //creat document、settion and table
            Spire.Doc.Section stuInfoSection = wordDocument.AddSection();
            Spire.Doc.Table   stuTable       = stuInfoSection.AddTable(true);
            stuTable.ResetCells(dataRowCount, columeCount);

            //set header
            Spire.Doc.TableRow row = stuTable.Rows[0];//initial TableRow
            row.IsHeader = true;
            for (int i = 0; i < columeCount; i++)
            {
                para = row.Cells[i].AddParagraph();
                TR   = para.AppendText(strHeader[i]);
            }

            //fill data
            for (int i = 1; i < dataRowCount; i++)
            {
                for (int j = 0; j < columeCount; j++)
                {
                    para = stuTable.Rows[i].Cells[j].AddParagraph();
                    TR   = para.AppendText(listStu[i - 1].GetValue(listStu[i - 1].propertyIndex[j]));
                }
            }

            //

            //save file
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "Word Documents(*.docx)|*.docx";
            var res = saveFileDialog.ShowDialog();

            if (res != true)
            {
                return;
            }
            path = saveFileDialog.FileName;
            MessageBox.Show(path);

            wordDocument.SaveToFile(@path, FileFormat.Docx);
            wordDocument.Close();
        }
예제 #4
0
        static void Main(string[] args)
        {
            // Changes \ to / in the path string
            string oldstr            = @"\";
            string newstr            = @"/";
            string pdf_path_original = string.Empty;

            // Tells the file path
            Console.WriteLine("FILE PATH: ");
            Console.OutputEncoding = Encoding.GetEncoding(932);
            Console.WriteLine("ファイル パス: ");
            pdf_path_original = Console.ReadLine();
            string pdf_path = pdf_path_original.Replace(oldstr, newstr);

            // Tells the file name
            Console.WriteLine(".pdf`s Name: ");
            Console.OutputEncoding = Encoding.GetEncoding(932);
            Console.WriteLine("ファイルの名前は: ");
            string pdf_file_name = Console.ReadLine();
            string path_n_name   = pdf_path + "/" + pdf_file_name + ".pdf";

            // Tells the file alignment
            Console.WriteLine("Text alignment: ");
            Console.OutputEncoding = Encoding.GetEncoding(932);
            Console.WriteLine("テキスト配置: ");
            Console.WriteLine("1: Left (左), and Right (右), or 2: Middle (真ん中)");
            string caseSwitch = Console.ReadLine();

            Console.WriteLine();


            // Tells the file start page and end page
            Console.WriteLine(".pdf`s Initial Page ");
            Console.OutputEncoding = Encoding.GetEncoding(932);
            Console.WriteLine("最初のページは: ");
            string startpage_string = Console.ReadLine();
            int    startpage        = Int32.Parse(startpage_string);

            Console.WriteLine(".pdf`s Last Page ");
            Console.OutputEncoding = Encoding.GetEncoding(932);
            Console.WriteLine("最後のページは: ");
            string endpage_string = Console.ReadLine();
            int    endpage        = Int32.Parse(endpage_string);

            // Creates blank pdf files
            for (int i = startpage; i <= endpage; i++)
            {
                string convi = i.ToString();
                // Creates a temp folder for the pdf files
                System.IO.Directory.CreateDirectory(pdf_path + "/" + "temp");
                System.IO.FileStream pdf_creator = new System.IO.FileStream(pdf_path + "/" + "temp" + "/" + convi + ".pdf", System.IO.FileMode.Create);
                pdf_creator.Close();
            }


            // Tells the attributes from the new pdf files, and the original pdf source
            iTextSharp.text.pdf.PdfReader       reader          = null;
            iTextSharp.text.Document            sourceDocument  = null;
            iTextSharp.text.pdf.PdfCopy         pdfCopyProvider = null;
            iTextSharp.text.pdf.PdfImportedPage importedPage    = null;

            reader         = new iTextSharp.text.pdf.PdfReader(path_n_name);
            sourceDocument = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(startpage));
            sourceDocument.Open();

            // Creates a .docx to receive the pdf's text
            Spire.Doc.Document word_doc = new Spire.Doc.Document();

            // Word doc formatting
            Spire.Doc.Section             word_doc_section        = word_doc.AddSection();
            Spire.Doc.Documents.Paragraph word_doc_paragraph      = word_doc_section.AddParagraph();
            Spire.Doc.Documents.Paragraph word_doc_paragraph_page = word_doc_section.AddParagraph();


            // Update those blank pdf files, inserting the copied pages into it
            try
            {
                for (int i = startpage; i <= endpage; i++)
                {
                    string convi = i.ToString();
                    pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(pdf_path + "/" + "temp" + "/" + convi + ".pdf", System.IO.FileMode.Append));
                    sourceDocument.Open();
                    importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                    pdfCopyProvider.AddPage(importedPage);
                }


                sourceDocument.Close();
                reader.Close();
            }


            // ERROR
            catch (Exception ex)
            {
                Console.WriteLine("Error! ");
                Console.OutputEncoding = Encoding.GetEncoding(932);
                Console.WriteLine("エラー ! ");
                throw ex;
            }


            // Collects the text without furigana from the listed pdf files
            switch (caseSwitch)
            {
            // case 1 reffers to the left and right alignments of the pdf text
            case "1":
                Console.WriteLine();
                for (int i = startpage; i <= endpage; i++)
                {
                    // the following refers to the int counter of pages being converted into string
                    string convi = i.ToString();
                    Console.OutputEncoding = Encoding.GetEncoding(932);
                    Console.WriteLine("今のページ: " + convi);
                    Console.WriteLine("Current Page: " + convi);

                    // the following refers to the bitmiracle api pdf to get the texts
                    using (BitMiracle.Docotic.Pdf.PdfDocument pdf_1 = new BitMiracle.Docotic.Pdf.PdfDocument(pdf_path + "/" + "temp" + "/" + convi + ".pdf"))
                    {
                        BitMiracle.Docotic.Pdf.PdfPage page = pdf_1.Pages[0];
                        foreach (PdfTextData data in page.GetWords())
                        {
                            if (data.FontSize > 6 && data.Position.X < 600)
                            {
                                string text = data.Text;
                                text.TrimEnd();
                                Console.OutputEncoding = Encoding.GetEncoding(932);
                                Console.WriteLine(text);
                                //word_builder.Writeln(text);
                                word_doc_paragraph.AppendText(text);
                            }
                        }
                        foreach (PdfTextData data in page.GetWords())
                        {
                            if (data.FontSize > 6 && data.Position.X > 600)
                            {
                                string text = data.Text;
                                text.TrimEnd();
                                Console.OutputEncoding = Encoding.GetEncoding(932);
                                Console.WriteLine(text);
                                word_doc_paragraph.AppendText(text);
                            }
                        }
                    }
                    // the following lines reffers to the space between pages of the pdf text
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();
                    // the followin reffers to the extra lines on word text


                    word_doc_paragraph.AppendText("                                        ");
                    word_doc_paragraph.AppendText("CURRENT PAGE: " + convi);
                    word_doc_paragraph = word_doc_section.AddParagraph();
                    word_doc.Sections[0].Paragraphs[i].AppendBreak(BreakType.PageBreak);
                }

                break;


            // case 2 reffers to the alignment of the pdf text that is centralized
            case "2":
                Console.WriteLine();
                for (int i = startpage; i <= endpage; i++)
                {
                    // the following refers to the int counter of pages being converted into string
                    string convi = i.ToString();
                    Console.OutputEncoding = Encoding.GetEncoding(932);
                    Console.WriteLine("今のページ: " + convi);
                    Console.WriteLine("Current Page: " + convi);

                    // the following refers to the bitmiracle api pdf to get the texts
                    using (BitMiracle.Docotic.Pdf.PdfDocument pdf_1 = new BitMiracle.Docotic.Pdf.PdfDocument(pdf_path + "/" + "temp" + "/" + convi + ".pdf"))
                    {
                        BitMiracle.Docotic.Pdf.PdfPage page = pdf_1.Pages[0];
                        foreach (PdfTextData data in page.GetWords())
                        {
                            if (data.FontSize > 6)
                            {
                                string text = data.Text;
                                text.TrimEnd();
                                Console.OutputEncoding = Encoding.GetEncoding(932);
                                Console.WriteLine(text);
                                word_doc_paragraph.AppendText(text);
                            }
                        }
                    }
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();

                    word_doc_paragraph.AppendText("                                        ");
                    word_doc_paragraph.AppendText("CURRENT PAGE: " + convi);
                    word_doc_paragraph = word_doc_section.AddParagraph();
                    word_doc.Sections[0].Paragraphs[i].AppendBreak(BreakType.PageBreak);
                }
                break;

            default:
                Console.OutputEncoding = Encoding.GetEncoding(932);
                Console.WriteLine("error! (エラー)");
                Console.ReadKey();
                break;
            }

            // The following refers to creating a .docx file, opening up the file and deleting the temp folder
            word_doc.SaveToFile(pdf_path + "/" + pdf_file_name + ".docx", FileFormat.Docx);
            System.IO.Directory.Delete(pdf_path + "/" + "temp", true);
            try
            {
                System.Diagnostics.Process.Start(pdf_path + "/" + pdf_file_name + ".docx");
            }
            catch
            {
                Console.WriteLine("Error! ");
                Console.OutputEncoding = Encoding.GetEncoding(932);
                Console.WriteLine("エラー ! ");
            }
        }
예제 #5
0
        public void Export(DataGridView dataGrid, string filename)
        {
            Spire.Doc.Document document = new Spire.Doc.Document();
            Spire.Doc.Section  section  = document.AddSection();
            section.PageSetup.Orientation = Spire.Doc.Documents.PageOrientation.Landscape;

            AddHeaderTitle(section);

            Spire.Doc.Table table       = section.AddTable(true);
            String[]        header      = { "ID", "Full Name", "Date of birth", "Gender", "Phone", "Email", "Position" };
            int             RowCount    = dataGrid.Rows.Count;
            int             ColumnCount = dataGrid.Columns.Count;

            String[][] data = new String[RowCount][];
            for (int i = 0; i < RowCount; i++)
            {
                data[i] = new String[ColumnCount];
            }

            //add rows
            for (int c = 0; c < ColumnCount; c++)
            {
                for (int r = 0; r < RowCount; r++)
                {
                    if (dataGrid.Rows[r].Cells[c].Value.GetType() == typeof(DateTime))
                    {
                        data[r][c] = ((DateTime)dataGrid.Rows[r].Cells[c].Value).ToString("dd/MM/yyyy");
                    }
                    else
                    {
                        data[r][c] = dataGrid.Rows[r].Cells[c].Value.ToString();
                    }
                }
            }

            table.ResetCells(data.Length + 1, header.Length);

            TableRow FRow = table.Rows[0];

            FRow.IsHeader = false;
            FRow.Height   = 23;
            //FRow.RowFormat.BackColor = Color.AliceBlue;
            for (int i = 0; i < header.Length; i++)
            {
                //Cell Alignment
                Spire.Doc.Documents.Paragraph p = FRow.Cells[i].AddParagraph();
                FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                //Data Format
                Spire.Doc.Fields.TextRange TR = p.AppendText(header[i]);
                TR.CharacterFormat.FontName  = "Calibri";
                TR.CharacterFormat.FontSize  = 14;
                TR.CharacterFormat.TextColor = Color.Black;
                TR.CharacterFormat.Bold      = true;
            }

            //Data Row
            for (int r = 0; r < data.Length; r++)
            {
                TableRow DataRow = table.Rows[r + 1];

                //Row Height
                DataRow.Height = 20;

                //C Represents Column.
                for (int c = 0; c < data[r].Length; c++)
                {
                    //Cell Alignment
                    DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    //Fill Data in Rows
                    Spire.Doc.Documents.Paragraph p2  = DataRow.Cells[c].AddParagraph();
                    Spire.Doc.Fields.TextRange    TR2 = p2.AppendText(data[r][c]);
                    //Format Cells
                    p2.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                    TR2.CharacterFormat.FontName  = "Calibri";
                    TR2.CharacterFormat.FontSize  = 12;
                    TR2.CharacterFormat.TextColor = Color.Black;
                }
            }

            //Save and Launch
            document.SaveToFile(filename);
            MessageBox.Show("Document Created Successfully!", "Export File", MessageBoxButtons.OK, MessageBoxIcon.Information);
            document.Close();
        }
        public static void Create()
        {
            try
            {
                //Laad de template in
                Document testdoc = new Document();
                testdoc.LoadFromFile(AppDomain.CurrentDomain.BaseDirectory + "\\Template.docx");
                //Maak table
                Section section = testdoc.Sections[0];
                Table   table   = section.Tables[0] as Table;
                //Table table = new Table(testdoc);
                table.ApplyStyle(DefaultTableStyle.MediumShading1Accent1);

                BookmarksNavigator navigator = new BookmarksNavigator(testdoc);

                TextBodyPart part = new TextBodyPart(testdoc);

                /*Aantal studenten /module/sesmter */

                //Deze tabel klopt
                //Aantal studenten / module /semster1
                AddTableInBookmark("select Module, count(Geslacht) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where MONTH([Module begindatum]) < 7  group by module ,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE())-5) order by  YEAR([Module begindatum]), semester", table, navigator, "TotaalAantalStudentenSem1", part);
                //Aantal studenten / module / semester2
                AddTableInBookmark("select Module, count(Geslacht) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where MONTH([Module begindatum]) > 7  group by module , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE())-5) order by  YEAR([Module begindatum]), semester", table, navigator, "TotaalAantalStudentenSem2", part);


                /*Geslaagde mensen / module per semester */
                //tabellen kloppen
                //Semester 1
                AddTableInBookmark("select Module, COUNT([Module attest]) as value , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) < 7 group by module , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by  YEAR([Module begindatum]), semester", table, navigator, "MensenGeslaagdSem1", part);

                //Geslaagde mensen / module per semester
                //semester 2
                AddTableInBookmark("select Module, COUNT([Module attest]) as value , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) > 7 group by module , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by  YEAR([Module begindatum]), semester", table, navigator, "MensenGeslaagdSem2", part);



                //Aantal afgestudeerden /semester

                //semester 1
                AddTableInBookmarkWithoutGroups("select COUNT(Stamnummer) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Toegepaste verpleegkunde (40 weken)' and[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) < 7 group by  CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum])", table, navigator, "AantalAfgestudeerdeStudentenSem1", part);

                //semester 2
                AddTableInBookmarkWithoutGroups("select COUNT(Stamnummer) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Toegepaste verpleegkunde (40 weken)' and[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) > 7 group by  CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum])", table, navigator, "AantalAfgestudeerdeStudentenSem2", part);


                //RedenStoppen
                //Klopt
                //semester 1
                AddTableInBookmark("select[Reden stoppen] ,count([Reden stoppen]) as value,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester , YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Reden stoppen] != '' and MONTH([Module begindatum]) < 7 group by [Reden stoppen],CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by  YEAR([Module begindatum]) ASC, semester ASC ", table, navigator, "RedenStoppenSem1", part);

                //semester 2
                AddTableInBookmark("select[Reden stoppen] ,count([Reden stoppen]) as value,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester , YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Reden stoppen] != '' and MONTH([Module begindatum]) > 7 group by [Reden stoppen],CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by  YEAR([Module begindatum]) ASC, semester ASC ", table, navigator, "RedenStoppenSem2", part);


                //school leren kennen
                //Klopt
                //semester 1
                AddTableInBookmark("select coalesce(nullif([School leren kennen],''), 'onbekend') as [school leren kennen], count([School leren kennen]) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Initiatie verpleegkunde (20 weken)' and MONTH([Module begindatum]) < 7 group by [School leren kennen], CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by  YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "SchoolLerenKennenSem1", part);

                //semester 2
                AddTableInBookmark("select coalesce(nullif([School leren kennen],''), 'onbekend') as [school leren kennen], count([School leren kennen]) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Initiatie verpleegkunde (20 weken)' and MONTH([Module begindatum]) > 7 group by [School leren kennen], CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by  YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "SchoolLerenKennenSem2", part);


                ////Aantal modules dat hernomen worden per module per semester*
                ////semester 1

                //// AddTableInBookmark("select Module, count(Module) as value ,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Verleende studiebewijzen 1ste zit] = '' and[Reden stoppen] = '' and[Klas vorig schooljaar] = '' and MONTH([Module begindatum]) < 7 group by Module,  CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by  YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "ModuleHernemenSem1", part);

                ////semester 2
                //if (ConnectDatabase.ExecuteQuery("create or alter view StudentenMetEenVorigeKlas as select Module as module,[Module attest] as moduleAttest, REPLACE([Klas vorig schooljaar], ' ', '') as VorigeKlas  ,Klas as Klas,[Module begindatum] as begindatum from tblStudentGegevens where[Klas vorig schooljaar]  != ''"))
                //{
                //    if (ConnectDatabase.ExecuteQuery())
                //        AddTableInBookmark("select Module, count(Module) as value ,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Verleende studiebewijzen 1ste zit] = '' and[Reden stoppen] = '' and[Klas vorig schooljaar] = '' and MONTH([Module begindatum]) > 7 group by Module,  CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by  YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "ModuleHernemenSem2", part);
                //}



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

                //Gemiddelde duur aantal semesters van de opleiding / student PER MOdule per afstudeerjaar (andere functie nodig)
                if (ConnectDatabase.ExecuteQuery("create or alter view GeslaagdeStudenten as select Stamnummer, Module from tblStudentGegevens where Module = 'Module Toegepaste verpleegkunde (40 weken)' and[Module attest] = 'Geslaagd'"))
                {
                    if (ConnectDatabase.ExecuteQuery("create or alter view AantalModulesPerAfgestudeerdeStudent as select count(tblStudentGegevens.Module) as aantalModules, GeslaagdeStudenten.Stamnummer from tblStudentGegevens INNER JOIN GeslaagdeStudenten ON tblStudentGegevens.Stamnummer = GeslaagdeStudenten.Stamnummer group by   GeslaagdeStudenten.Stamnummer"))
                    {
                        AddTableInBookmarkWithoutGroups("select ROUND(AVG(CAST(AantalModulesPerAfgestudeerdeStudent.aantalModules as float)),2)  as value, YEAR([Module begindatum]) as jaar from tblStudentGegevens INNER JOIN AantalModulesPerAfgestudeerdeStudent ON tblStudentGegevens.Stamnummer = AantalModulesPerAfgestudeerdeStudent.Stamnummer Group by YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5)", table, navigator, "GemiddeldeDuur", part);
                    }
                }


                //Percentage meisjes jongens
                if (ConnectDatabase.ExecuteQuery("create or alter view TotaalAantalStudentenPerSemester as select Count(Stamnummer) as 'value' , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens group  by CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) "))
                {
                    if (ConnectDatabase.ExecuteQuery("create or alter view TotaalAantalVrouwenPerSemester as select Count(Stamnummer) as 'value', CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Geslacht = 'V' group  by CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) "))
                    {
                        if (ConnectDatabase.ExecuteQuery("create or alter view TotaalAantalMannenPerSemester as select Count(Stamnummer) as 'value' , Geslacht, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Geslacht = 'M' group  by Geslacht, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5)"))
                        {
                            //Mannen
                            AddTableInBookmarkWithoutGroups("select CAST(ROUND(CAST(TotaalAantalMannenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalMannenPerSemester on(TotaalAantalMannenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalMannenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalMannenPerSemester.semester = 1 ", table, navigator, "VerhoudingManSem1", part);
                            AddTableInBookmarkWithoutGroups("select CAST(ROUND(CAST(TotaalAantalMannenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalMannenPerSemester on(TotaalAantalMannenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalMannenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalMannenPerSemester.semester = 2 ", table, navigator, "VerhoudingManSem2", part);

                            //Vrouwen
                            AddTableInBookmarkWithoutGroups(" select CAST(ROUND(CAST(TotaalAantalVrouwenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalVrouwenPerSemester on(TotaalAantalVrouwenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalVrouwenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalVrouwenPerSemester.semester = 1", table, navigator, "VerhoudingVrouwSem1", part);
                            AddTableInBookmarkWithoutGroups(" select CAST(ROUND(CAST(TotaalAantalVrouwenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalVrouwenPerSemester on(TotaalAantalVrouwenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalVrouwenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalVrouwenPerSemester.semester = 2", table, navigator, "VerhoudingVrouwSem2", part);
                        }
                    }
                }



                testdoc.SaveToFile(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\output.docx", FileFormat.Docx2013);
                System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\output.docx");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Er is een onverwachte fout opgetreden bij het exporten van de data: " + ex, "Fout", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
예제 #7
0
        public void CreateDocument(MemberInfo_ViewModel info, Image image, ref int i)
        {
            //Create New Word
            Document doc = new Document();

            if (image != null)
            {
                Image resize = (Image)(new Bitmap(image, new System.Drawing.Size(900, 1000)));
                //PictureWatermark picture = new PictureWatermark();
                //picture.Picture = image;
                ////picture.IsWashout = false;
                //doc.Watermark = picture;

                doc.Background.Type    = BackgroundType.Picture;
                doc.Background.Picture = resize;
            }

            //Add Section
            Spire.Doc.Section section = doc.AddSection();
            section.PageSetup.PageSize = PageSize.A4;
            //section.PageSetup.Margins.Top = 150;
            //section.PageSetup.PageBorderIncludeHeader = false;
            //section.PageSetup.Margins.Bottom = 0;
            //section.PageSetup.Margins.Left = 89.85f;
            //section.PageSetup.Margins.Right = 89.85f;

            section.PageSetup.Borders.Bottom.Space = 0;
            //Add Paragraph
            Paragraph pHeader = section.AddParagraph();
            //Header
            TextRange textRangel = pHeader.AppendText("HỒ SƠ HỌC VIÊN");

            textRangel.CharacterFormat.Bold      = true;
            textRangel.CharacterFormat.TextColor = System.Drawing.Color.Blue;
            textRangel.CharacterFormat.FontSize  = 24;
            textRangel.CharacterFormat.FontName  = "Calibri Light (Headings)";
            pHeader.Format.HorizontalAlignment   = Spire.Doc.Documents.HorizontalAlignment.Center;
            pHeader.Format.AfterSpacing          = 5;
            //SKU
            draw(doc, 210, 22, 20, 5, "SKU: " + info.SKU);
            //Register Number
            draw(doc, 210, 22, 260, -9, "SỐ ĐĂNG KÝ: " + info.RegisterNumber);
            //Name
            draw(doc, 450, 22, 20, 8, "HỌ TÊN: " + info.FullName);
            //Quốc Tịch
            draw(doc, 450, 22, 20, 25, "QUỐC TỊCH: " + info.Nation);
            //Address
            draw(doc, 450, 22, 20, 42, "ĐỊA CHỈ: " + info.Address);
            //PHONE
            draw(doc, 450, 22, 20, 60, "SỐ ĐIỆN THOẠI: " + info.PhoneNumber);
            //Image
            imageDraw(doc, 145, 115, 15, 75, info.Image);
            //Register Day
            draw(doc, 320, 22, 150, 67, "NGÀY ĐĂNG KÝ: " + info.Register_day.ToShortDateString());
            // Day of Birth
            draw(doc, 320, 22, 150, 90, "NGÀY SINH : " + info.Day_of_Birth.ToShortDateString());
            //Place of Birth
            draw(doc, 320, 22, 150, 115, "NƠI SINH: " + info.Place_of_Birth);
            //Class
            draw(doc, 320, 22, 150, 139, "LỚP: " + info.Class_Name);
            //Cap 1-6

            draw(doc, 450, 22, 20, 160, "CẤP 6: " + (info.listLevel["Cap6"] != DateTime.MinValue ? info.listLevel["Cap6"].ToShortDateString() : ""));
            draw(doc, 450, 22, 20, 177, "CẤP 5: " + (info.listLevel["Cap5"] != DateTime.MinValue ? info.listLevel["Cap5"].ToShortDateString() : ""));
            draw(doc, 450, 22, 20, 193, "CẤP 4: " + (info.listLevel["Cap4"] != DateTime.MinValue ? info.listLevel["Cap4"].ToShortDateString() : ""));
            draw(doc, 450, 22, 20, 209, "CẤP 3: " + (info.listLevel["Cap3"] != DateTime.MinValue ? info.listLevel["Cap3"].ToShortDateString() : ""));
            draw(doc, 450, 22, 20, 225, "CẤP 2: " + (info.listLevel["Cap2"] != DateTime.MinValue ? info.listLevel["Cap2"].ToShortDateString() : ""));
            draw(doc, 450, 22, 20, 240, "CẤP 1: " + (info.listLevel["Cap1"] != DateTime.MinValue ? info.listLevel["Cap1"].ToShortDateString() : ""));

            draw(doc, 210, 22, 20, 260, "I DAN VN: " + (info.listLevel["DANVN1"] != DateTime.MinValue ? info.listLevel["DANVN1"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 278, "II DAN VN: " + (info.listLevel["DANVN2"] != DateTime.MinValue ? info.listLevel["DANVN2"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 296, "III DAN VN: " + (info.listLevel["DANVN3"] != DateTime.MinValue ? info.listLevel["DANVN3"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 314, "IV DAN VN: " + (info.listLevel["DANVN4"] != DateTime.MinValue ? info.listLevel["DANVN4"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 332, "V DAN VN: " + (info.listLevel["DANVN5"] != DateTime.MinValue ? info.listLevel["DANVN5"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 350, "VI DAN VN: " + (info.listLevel["DANVN6"] != DateTime.MinValue ? info.listLevel["DANVN6"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 368, "VII DAN VN: " + (info.listLevel["DANVN7"] != DateTime.MinValue ? info.listLevel["DANVN7"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 384, "VIII DAN VN: " + (info.listLevel["DANVN8"] != DateTime.MinValue ? info.listLevel["DANVN8"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 150, "I DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI1"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI1"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 168, "II DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI2"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI2"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 185, "III DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI3"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI3"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 204, "IV DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI4"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI4"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 220, "V DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI5"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI5"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 238, "VI DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI6"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI6"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 256, "VII DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI7"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI7"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 274, "VIII DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI8"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI8"].ToShortDateString() : ""));


            //Save and launch
            i++;
            doc.SaveToFile("MemberInfo" + i + ".docx", FileFormat.Docx);

            Process myProcess = new Process();

            try
            {
                myProcess = Process.Start("MemberInfo" + i + ".docx");
            }
            catch { }
        }
예제 #8
0
        public IActionResult Batchs(string command, string ids)
        {
            var          response       = ResponseModelFactory.CreateInstance;
            string       sWebRootFolder = _hostingEnvironment.WebRootPath + "\\UploadFiles\\ImportUserInfoWord\\";
            var          timeInfo       = DateTime.Now.ToString("yyyyMMddHHmmss");
            var          wordName       = timeInfo + "address.docx";
            string       wordUrl        = sWebRootFolder + wordName;
            MemoryStream ms             = new MemoryStream();
            XWPFDocument m_Docx         = new XWPFDocument();

            m_Docx.Write(ms);
            ms.Flush();
            SaveToFile(ms, wordUrl);
            List <string> list = new List <string>();


            using (_dbContext)
            {
                //document111.LoadFromFile(sWebRootFolder + "test.docx");
                Document document111 = new Document();
                document111.LoadFromFile(wordUrl);
                Section section = document111.Sections[0];
                document111.Watermark = null;
                section.Paragraphs[0].AppendBookmarkStart("picture");
                section.Paragraphs[0].AppendBookmarkEnd("picture");
                var parameters     = ids.Split(",").Select((id, index) => new SqlParameter(string.Format("@p{0}", index), id)).ToList();
                var parameterNames = string.Join(", ", parameters.Select(p => p.ParameterName));
                var entities       = _dbContext.SystemUser.Where(x => ids.IndexOf(x.SystemUserUuid.ToString()) >= 0).ToList();
                for (int i = 0; i < entities.Count; i++)
                {
                    var pata = _hostingEnvironment.WebRootPath + EWM.GetEWM2("d_" + entities[i].SystemUserUuid.ToString(), _hostingEnvironment, entities[i].RealName);
                    //实例化BookmarksNavigator类,指定需要添加图片的书签“”
                    BookmarksNavigator bn = new BookmarksNavigator(document111);
                    bn.MoveToBookmark("picture", true, true);
                    //添加段落,加载图片并插入到段落
                    Section section0 = document111.AddSection();
                    Spire.Doc.Documents.Paragraph paragraph = section0.AddParagraph();
                    Image image = Image.FromFile(pata);

                    //DocPicture picture = paragraph.AppendPicture(image);
                    DocPicture picture = document111.Sections[0].Paragraphs[0].AppendPicture(image);
                    picture.Width  = 160;
                    picture.Height = 180;
                    //picture.HorizontalPosition = 100.0f;
                    //picture.VerticalPosition = 100.0f;
                    bn.InsertParagraph(paragraph);
                    document111.Sections.Remove(section0);
                    //string output = sWebRootFolder + "test.docx";
                    document111.SaveToFile(wordUrl, FileFormat.Docx);
                }
                list.Add(wordUrl);
                //关闭进程
                document111.Dispose();
                var time  = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                var check = ZIP.CompressMulti(list, _hostingEnvironment.WebRootPath + "\\UploadFiles\\EWM\\" + time, false);
                if (check)
                {
                    response.SetSuccess("导出成功");
                    response.SetData("\\UploadFiles\\EWM\\" + time + ".zip");
                }
                else
                {
                    response.SetFailed("导出失败");
                }
                return(Ok(response));
            }
        }
예제 #9
0
        public static void RequestDocument(String[][] data, int gap)
        {
            var systemDateTime   = DateTime.Now;
            var persianDateTimem = new PersianCalendar();
            var persianDate      = $"{persianDateTimem.GetYear(systemDateTime)}/{persianDateTimem.GetMonth(systemDateTime)}" +
                                   $"/{persianDateTimem.GetDayOfMonth(systemDateTime)}";
            Document doc = new Document();

            {
                var mainSection = doc.AddSection();
                mainSection.PageSetup.PageSize = PageSize.A5;
                var mainTitle = mainSection.AddParagraph();
                mainTitle.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                mainTitle.Text = "هیئت امنا بانو نسیبه";
                var style = new ParagraphStyle(doc)
                {
                    Name = "MailTitle", CharacterFormat = { FontName = "Arial", FontSize = 30, Bold = true }
                };
                doc.Styles.Add(style);
                mainTitle.ApplyStyle(style.Name);
            }
            {
                var documentNumber = doc.LastSection.AddParagraph();
                documentNumber.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right;
                documentNumber.Text = $"{Properties.Settings.Default.Request} : شماره";
                Properties.Settings.Default.Request++;
                Properties.Settings.Default.Save();
                var style = new ParagraphStyle(doc)
                {
                    Name = "DocumentNumber", CharacterFormat = { FontName = "Arial", FontSize = 10 }
                };
                doc.Styles.Add(style);
                documentNumber.ApplyStyle(style.Name);
            }
            {
                var date = doc.LastSection.AddParagraph();
                date.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right;
                date.Text = $"{persianDate} : تاریخ";
                var style = new ParagraphStyle(doc)
                {
                    Name = "Date", CharacterFormat = { FontName = "Arial", FontSize = 10 }
                };
                doc.Styles.Add(style);
                date.ApplyStyle(style.Name);
            }
            {
                var documentTitle = doc.LastSection.AddParagraph();
                documentTitle.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                documentTitle.Text = "برگ درخواست خرید";
                var style = new ParagraphStyle(doc)
                {
                    Name = "DocumentTitle", CharacterFormat = { FontName = "Arial", FontSize = 22, Bold = true }
                };
                doc.Styles.Add(style);
                documentTitle.ApplyStyle(style.Name);
            }
            {
                var descriptionParagraph1 = doc.LastSection.AddParagraph();
                descriptionParagraph1.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right;
                descriptionParagraph1.Text = "خواهشمند است لوازم مشروحه ذیل را که مورد نیاز قسمت";
                var style = new ParagraphStyle(doc)
                {
                    Name = "descriptionParagraph1", CharacterFormat = { FontName = "Arial", FontSize = 14 }
                };
                doc.Styles.Add(style);
                descriptionParagraph1.ApplyStyle(style.Name);
            }
            {
                var descriptionParagraph2 = doc.LastSection.AddParagraph();
                descriptionParagraph2.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right;
                string txt = ".می باشد تهیه و تحویل نماید";
                descriptionParagraph2.Text = txt;
                var style = new ParagraphStyle(doc)
                {
                    Name = "descriptionParagraph2", CharacterFormat = { FontName = "Arial", FontSize = 14 }
                };
                doc.Styles.Add(style);
                descriptionParagraph2.ApplyStyle(style.Name);
            }
            Spire.Doc.Section s      = doc.LastSection;
            String[]          Header = { "ملاحضات", "شرح", "تعداد", "شماره کالا" };
            Table             table  = s.AddTable(true);

            table.ResetCells(data.Length + 1 - gap, Header.Length);
            var FRow = table.Rows[0];

            FRow.IsHeader = true;
            FRow.Height   = 20;
            for (int i = 0; i < Header.Length; i++)
            {
                //Cell Alignment
                var p = FRow.Cells[i].AddParagraph();
                FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                if (i == 0 || i == 1)
                {
                    FRow.Cells[i].Width = 120;
                }
                p.Format.HorizontalAlignment = HorizontalAlignment.Center;
                //Fill Header data and Format the Cells
                var TR = p.AppendText(Header[i]);
                TR.CharacterFormat.FontName  = "Arial";
                TR.CharacterFormat.FontSize  = 10;
                TR.CharacterFormat.TextColor = System.Drawing.Color.Black;
                TR.CharacterFormat.Bold      = true;
            }
            for (int r = 0; r < data.Length - gap; r++)
            {
                var dataRow = table.Rows[r + 1];
                //Row Height
                dataRow.Height = 15;
                //C Represents Column.
                for (int c = 0; c < data[r].Length; c++)
                {
                    //Cell Alignment
                    dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    //Fill Data in Rows
                    var p2 = dataRow.Cells[c].AddParagraph();
                    p2.Format.HorizontalAlignment = HorizontalAlignment.Right;
                    p2.Text = data[r][c];
                }
            }
            var subPragraph1 = doc.LastSection.AddParagraph();

            subPragraph1.Text = Environment.NewLine + "درخواست کننده\t\t";
            subPragraph1.AppendText("کارپردازی\t\t");
            subPragraph1.AppendText("رئیس حسابداری");
            subPragraph1.Format.HorizontalAlignment = HorizontalAlignment.Center;
            var subTextStyle = new ParagraphStyle(doc)
            {
                Name = "SubText", CharacterFormat = { FontName = "Arial", FontSize = 14 }
            };

            doc.Styles.Add(subTextStyle);
            subPragraph1.ApplyStyle(subTextStyle.Name);
            if (!Directory.Exists($"Documents"))
            {
                Directory.CreateDirectory($"Documents");
            }
            var documentPathName = $"Documents\\Request({ persianDateTimem.GetYear(systemDateTime)}-" +
                                   $"{ persianDateTimem.GetMonth(systemDateTime)}" + $"-" +
                                   $"{persianDateTimem.GetDayOfMonth(systemDateTime)})(" +
                                   $"{persianDateTimem.GetHour(systemDateTime)}-" +
                                   $"{persianDateTimem.GetMinute(systemDateTime)}-" +
                                   $"{persianDateTimem.GetSecond(systemDateTime)}).docx";

            doc.SaveToFile(documentPathName);
            System.Diagnostics.Process.Start(documentPathName);
        }
예제 #10
0
        /// <summary>
        /// 透過既有的套印檔匯出 Word 文件 (以「編輯書籤內容」方式套印)
        /// </summary>
        /// <param name="result">回傳: 執行結果</param>
        /// <param name="msg">回傳: 訊息</param>
        /// <returns>串流資訊</returns>
        public byte[] ExportResumeByDocx_Bookmark(out bool result, out string msg)
        {
            result = true;
            msg    = "";
            MemoryStream ms = new MemoryStream();

            try
            {
                Spire.Doc.Document document = new Spire.Doc.Document();

                //載入套印檔
                //注意: 實際運作時,若同一時間有兩位以上使用者同時進行套印,會產生「無法開啟已開啟檔案」的錯誤
                //建議實作時,一個使用者執行匯出動作時先複製一個套印檔,完成套印後再將複製的檔案刪除,即可避開錯誤
                document.LoadFromFile(HttpContext.Current.Server.MapPath("~/App_Data/MyResumeSample_Bookmark.docx"));

                #region 定義樣式

                //定義樣式 BasicStyle: 一般段落文字
                ParagraphStyle style = new ParagraphStyle(document)
                {
                    Name = "Basic"
                };
                //style.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Justify;
                style.CharacterFormat.FontName = "標楷體";
                style.CharacterFormat.FontSize = 12;
                document.Styles.Add(style);

                #endregion

                //取得要套印的內容
                Resume model = new Resume();

                #region 套印內容

                BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);

                Spire.Doc.Bookmark bookmark = document.Bookmarks.FindByName("NAME");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("NAME");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Name) ? "" : model.Name, false);
                }
                bookmark = document.Bookmarks.FindByName("GENDER");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("GENDER");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Gender) ? "" : model.Gender, false);
                }
                bookmark = document.Bookmarks.FindByName("EMAIL");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("EMAIL");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Email) ? "" : model.Email, false);
                }
                bookmark = document.Bookmarks.FindByName("ADDRESS");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("ADDRESS");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Address) ? "" : model.Address, false);
                }
                bookmark = document.Bookmarks.FindByName("PHONE");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("PHONE");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Phone) ? "" : model.Phone, false);
                }
                bookmark = document.Bookmarks.FindByName("MOBILE");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("MOBILE");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Mobile) ? "" : model.Mobile, false);
                }



                Spire.Doc.Section tempSection = document.AddSection();
                string            html;
                ParagraphBase     replacementFirstItem;
                ParagraphBase     replacementLastItem;
                TextBodySelection selection;
                TextBodyPart      part;

                //HTML Contents: Desciprion1
                bookmark = document.Bookmarks.FindByName("DESCRIPTION1");
                if (bookmark != null)
                {
                    html = string.IsNullOrEmpty(model.Description1) ? "" : HttpUtility.HtmlDecode(model.Description1);
                    tempSection.AddParagraph().AppendHTML(html);
                    replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
                    replacementLastItem  = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
                    selection            = new TextBodySelection(replacementFirstItem, replacementLastItem);
                    //將內容各段落套用指定的樣式
                    for (int i = 0; i < tempSection.Paragraphs.Count; i++)
                    {
                        tempSection.Paragraphs[i].ApplyStyle("Basic");
                    }
                    part = new TextBodyPart(selection);

                    // locate the bookmark
                    bookmarkNavigator.MoveToBookmark("DESCRIPTION1");
                    //replace the content of bookmark
                    bookmarkNavigator.ReplaceBookmarkContent(part);
                    //remove temp section
                    document.Sections.Remove(tempSection);
                }

                //HTML Contents: Desciprion2
                bookmark = document.Bookmarks.FindByName("DESCRIPTION2");
                if (bookmark != null)
                {
                    tempSection = document.AddSection();
                    html        = string.IsNullOrEmpty(model.Description2) ? "" : HttpUtility.HtmlDecode(model.Description2);
                    tempSection.AddParagraph().AppendHTML(html);
                    replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
                    replacementLastItem  = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
                    selection            = new TextBodySelection(replacementFirstItem, replacementLastItem);
                    part = new TextBodyPart(selection);

                    bookmarkNavigator.MoveToBookmark("DESCRIPTION2");
                    bookmarkNavigator.ReplaceBookmarkContent(part);
                    document.Sections.Remove(tempSection);
                }

                //圖片
                bookmark = document.Bookmarks.FindByName("IMG");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("IMG");
                    Spire.Doc.Section             section_img   = document.AddSection();
                    Spire.Doc.Documents.Paragraph paragraph_img = section_img.AddParagraph();
                    Image      img     = Image.FromFile(HttpContext.Current.Server.MapPath("~/App_Data/Penguins.jpg"));
                    DocPicture picture = paragraph_img.AppendPicture(img);

                    bookmarkNavigator.InsertParagraph(paragraph_img);
                    document.Sections.Remove(section_img);
                }
                #endregion

                #region 動態新增表格

                if (model.JobHistory.Count > 0)
                {
                    Spire.Doc.Section s      = document.AddSection();
                    Spire.Doc.Table   table  = s.AddTable(true);
                    string[]          Header = { "序號", "任職公司", "職稱", "開始時間", "結束時間" };

                    //Add Cells
                    table.ResetCells(model.JobHistory.Count + 1, Header.Length);

                    //Header Row
                    TableRow FRow = table.Rows[0];
                    FRow.IsHeader = true;
                    for (int i = 0; i < Header.Length; i++)
                    {
                        Spire.Doc.Documents.Paragraph p = FRow.Cells[i].AddParagraph();
                        FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        p.Format.HorizontalAlignment = HorizontalAlignment.Center;

                        TextRange TR = p.AppendText(Header[i]);
                        TR.CharacterFormat.Bold = true;
                    }

                    //Data Row
                    model.JobHistory = model.JobHistory.OrderBy(x => x.StartDT).ToList();
                    for (int r = 0; r < model.JobHistory.Count; r++)
                    {
                        TableRow DataRow = table.Rows[r + 1];
                        string[] data    = new string[] { (r + 1).ToString(), model.JobHistory[r].CompanyName, model.JobHistory[r].JobTitle, (model.JobHistory[r].StartDT.HasValue ? model.JobHistory[r].StartDT.Value.ToShortDateString() : ""), (model.JobHistory[r].EndDT.HasValue ? model.JobHistory[r].EndDT.Value.ToShortDateString() : "") };

                        //Columns.
                        for (int c = 0; c < data.Length; c++)
                        {
                            //Cell Alignment
                            DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                            //Fill Data in Rows
                            Spire.Doc.Documents.Paragraph p2 = DataRow.Cells[c].AddParagraph();
                            TextRange TR2 = p2.AppendText(data[c]);

                            //Format Cells
                            p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
                        }
                    }

                    bookmarkNavigator.MoveToBookmark("TABLE");
                    bookmarkNavigator.InsertTable(table);
                }

                #endregion

                #region 套用樣式

                //套用文章段落樣式
                for (int s = 0; s < document.Sections.Count; s++)
                {
                    Spire.Doc.Section sections = document.Sections[s];
                    //套用文章段落樣式
                    for (int p = 0; p < sections.Paragraphs.Count; p++)
                    {
                        Spire.Doc.Documents.Paragraph pgh = sections.Paragraphs[p];
                        pgh.ApplyStyle("Basic");
                        pgh.Format.BeforeSpacing = 12;
                    }

                    //套用表格樣式
                    for (int t = 0; t < document.Sections[s].Tables.Count; t++)
                    {
                        Spire.Doc.Table table = (Spire.Doc.Table)document.Sections[s].Tables[t];
                        table.PreferredWidth            = new PreferredWidth(WidthType.Percentage, 100);
                        table.TableFormat.IsAutoResized = true;

                        //set table border
                        //table.TableFormat.Borders.Right.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Left.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Top.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Horizontal.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Vertical.BorderType = Spire.Doc.Documents.BorderStyle.Thick;

                        for (int tr = 0; tr < table.Rows.Count; tr++)
                        {
                            for (int td = 0; td < table.Rows[tr].Cells.Count; td++)
                            {
                                for (int t_ph = 0; t_ph < table.Rows[tr].Cells[td].Paragraphs.Count; t_ph++)
                                {
                                    table.Rows[tr].Cells[td].Paragraphs[t_ph].ApplyStyle("Basic");
                                }
                            }
                        }
                    }
                }

                #endregion

                //匯出
                document.SaveToStream(ms, FileFormat.Docx);
            }
            catch (Exception ex)
            {
                result = false;
                msg    = ex.Message;
            }

            if (result)
            {
                return(ms.ToArray());
            }
            else
            {
                return(null);
            }
        }
예제 #11
0
        /// <summary>
        /// 透過 HTML Tag 匯出 Word 文件
        /// </summary>
        /// <param name="result">回傳: 執行結果</param>
        /// <param name="msg">回傳: 訊息</param>
        /// <returns>串流資訊</returns>
        public byte[] ExportResumeByHtml(out bool result, out string msg)
        {
            result = true;
            msg    = "";
            MemoryStream ms = new MemoryStream();

            try
            {
                Spire.Doc.Document document = new Spire.Doc.Document();

                #region 文件內容

                //建立/取得要匯出的內容
                Resume        model = new Resume();
                StringBuilder html  = new StringBuilder();
                html.Append("Name: " + model.Name + "<br />");
                html.Append("Gender: " + model.Gender + "<br />");
                html.Append("Email: " + model.Email + "<br />");
                html.Append("Address: " + model.Address + "<br />");
                html.Append("Phone: " + model.Phone + "<br />");
                html.Append("Mobile: " + model.Mobile + "<br />");
                html.Append("Description1:<br />" + HttpUtility.HtmlDecode(model.Description1) + "<br /></p>");
                html.Append("Description2:<br />" + HttpUtility.HtmlDecode(model.Description2) + "<br /></p>");

                if (model.JobHistory.Count > 0)
                {
                    int i = 1;
                    model.JobHistory = model.JobHistory.OrderBy(x => x.StartDT).ToList();
                    html.Append("<p>簡歷</p>");
                    html.Append("<table><tr><th>項目</th><th>任職</th><th>職稱</th><th>開始時間</th><th>結束時間</th></tr>");
                    foreach (var h in model.JobHistory)
                    {
                        html.Append("<tr>");
                        html.Append("<td>" + i.ToString() + "</td>");
                        html.Append("<td>" + h.CompanyName + "</td>");
                        html.Append("<td>" + h.JobTitle + "</td>");
                        html.Append("<td>" + (h.StartDT.HasValue ? h.StartDT.Value.ToShortDateString() : "") + "</td>");
                        html.Append("<td>" + (h.EndDT.HasValue ? h.EndDT.Value.ToShortDateString() : "") + "</td>");
                        html.Append("</tr>");
                        i++;
                    }
                    html.Append("</table>");
                }

                #endregion

                //將 HTML 載入至 Document
                document.LoadHTML(new StringReader(html.ToString()), XHTMLValidationType.None);

                #region 設定樣式

                //一般段落文字
                ParagraphStyle style = new ParagraphStyle(document)
                {
                    Name = "BasicStyle"
                };
                //style.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Justify;
                style.CharacterFormat.FontName = "標楷體";
                style.CharacterFormat.FontSize = 12;
                document.Styles.Add(style);

                #endregion

                #region 套用樣式

                for (int s = 0; s < document.Sections.Count; s++)
                {
                    Spire.Doc.Section section = document.Sections[s];
                    //套用文章段落樣式
                    for (int p = 0; p < section.Paragraphs.Count; p++)
                    {
                        Spire.Doc.Documents.Paragraph pgh = section.Paragraphs[p];
                        pgh.ApplyStyle("BasicStyle");
                        pgh.Format.BeforeSpacing = 10;
                    }

                    //套用表格樣式
                    for (int t = 0; t < document.Sections[s].Tables.Count; t++)
                    {
                        Spire.Doc.Table table = (Spire.Doc.Table)document.Sections[s].Tables[t];
                        table.PreferredWidth            = new PreferredWidth(WidthType.Percentage, 100);
                        table.TableFormat.IsAutoResized = true;

                        //set table border
                        table.TableFormat.Borders.Right.BorderType      = Spire.Doc.Documents.BorderStyle.Thick;
                        table.TableFormat.Borders.Left.BorderType       = Spire.Doc.Documents.BorderStyle.Thick;
                        table.TableFormat.Borders.Top.BorderType        = Spire.Doc.Documents.BorderStyle.Thick;
                        table.TableFormat.Borders.Bottom.BorderType     = Spire.Doc.Documents.BorderStyle.Thick;
                        table.TableFormat.Borders.Horizontal.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        table.TableFormat.Borders.Vertical.BorderType   = Spire.Doc.Documents.BorderStyle.Thick;

                        for (int tr = 0; tr < table.Rows.Count; tr++)
                        {
                            for (int td = 0; td < table.Rows[tr].Cells.Count; td++)
                            {
                                for (int t_ph = 0; t_ph < table.Rows[tr].Cells[td].Paragraphs.Count; t_ph++)
                                {
                                    table.Rows[tr].Cells[td].Paragraphs[t_ph].ApplyStyle("BasicStyle");
                                }
                            }
                        }
                    }
                }

                #endregion

                //匯出
                document.SaveToStream(ms, FileFormat.Docx);
            }
            catch (Exception ex)
            {
                msg    = ex.Message;
                result = false;
            }

            if (result)
            {
                return(ms.ToArray());
            }
            else
            {
                return(null);
            }
        }
예제 #12
0
        /// <summary>
        /// 透過既有的套印檔匯出 Word 文件 (以「取代文字」方式套印)
        /// </summary>
        /// <param name="result">回傳: 執行結果</param>
        /// <param name="msg">回傳: 訊息</param>
        /// <returns>串流資訊</returns>
        public byte[] ExportResumeByDocx_ReplaceText(out bool result, out string msg)
        {
            result = true;
            msg    = "";
            MemoryStream ms = new MemoryStream();

            try
            {
                Spire.Doc.Document document = new Spire.Doc.Document();

                //載入套印檔
                //注意: 實際運作時,若同一時間有兩位以上使用者同時進行套印,會產生「無法開啟已開啟檔案」的錯誤
                //建議實作時,一個使用者執行匯出動作時先複製一個套印檔,完成套印後再將複製的檔案刪除,即可避開錯誤
                document.LoadFromFile(HttpContext.Current.Server.MapPath("~/App_Data/MyResumeSample.docx"));

                #region 定義樣式

                //定義樣式 BasicStyle: 一般段落文字
                ParagraphStyle style = new ParagraphStyle(document)
                {
                    Name = "Basic"
                };
                //style.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Justify;
                style.CharacterFormat.FontName = "標楷體";
                style.CharacterFormat.FontSize = 12;
                document.Styles.Add(style);

                #endregion

                //取得要套印的內容
                Resume model = new Resume();

                #region 套印內容

                document.Replace("{$Name$}", string.IsNullOrEmpty(model.Name) ? "" : model.Name, false, true);
                document.Replace("{$Gender$}", string.IsNullOrEmpty(model.Gender) ? "" : model.Gender, false, true);
                document.Replace("{$Email$}", string.IsNullOrEmpty(model.Email) ? "" : model.Email, false, true);
                document.Replace("{$Address$}", string.IsNullOrEmpty(model.Address) ? "" : model.Address, false, true);
                document.Replace("{$Phone$}", string.IsNullOrEmpty(model.Phone) ? "" : model.Phone, false, true);
                document.Replace("{$Mobile$}", string.IsNullOrEmpty(model.Mobile) ? "" : model.Mobile, false, true);

                //包含 HTML 字串需放置在 paragraph 內,
                //因此套印檔中的 {$Description1$} 及 {$Description2$} 需透過「以 paragraph 取代文字」方式替代
                //Replace {$Description1$} with paragraph
                TextSelection selection = document.FindString("{$Description1$}", false, true);
                TextRange     range     = selection.GetAsOneRange();
                Spire.Doc.Documents.Paragraph paragraph = range.OwnerParagraph;
                paragraph.ApplyStyle("Basic");
                paragraph.Replace("{$Description1$}", "", false, false);
                paragraph.AppendHTML(string.IsNullOrEmpty(model.Description1) ? "" : HttpUtility.HtmlDecode(model.Description1));

                //Replace {$Description2$} with paragraph
                selection = document.FindString("{$Description2$}", false, true);
                range     = selection.GetAsOneRange();
                paragraph = range.OwnerParagraph;
                paragraph.ApplyStyle("Basic");
                paragraph.Replace("{$Description2$}", "", false, false);
                paragraph.AppendHTML(string.IsNullOrEmpty(model.Description2) ? "" : HttpUtility.HtmlDecode(model.Description2));

                //Replace {$Img$} with Image
                DocPicture pic = new DocPicture(document);
                pic.LoadImage(Image.FromFile(HttpContext.Current.Server.MapPath("~/App_Data/Penguins.jpg")));

                selection = document.FindString("{$Img$}", false, true);
                range     = selection.GetAsOneRange();
                range.OwnerParagraph.ChildObjects.Insert(0, pic);
                range.OwnerParagraph.ChildObjects.Remove(range);

                #endregion

                #region 動態新增表格

                if (model.JobHistory.Count > 0)
                {
                    Spire.Doc.Section s      = document.AddSection();
                    Spire.Doc.Table   table  = s.AddTable(true);
                    string[]          Header = { "序號", "任職公司", "職稱", "開始時間", "結束時間" };

                    //Add Cells
                    table.ResetCells(model.JobHistory.Count + 1, Header.Length);

                    //Header Row
                    TableRow FRow = table.Rows[0];
                    FRow.IsHeader = true;
                    for (int i = 0; i < Header.Length; i++)
                    {
                        Spire.Doc.Documents.Paragraph p = FRow.Cells[i].AddParagraph();
                        FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        p.Format.HorizontalAlignment = HorizontalAlignment.Center;

                        TextRange TR = p.AppendText(Header[i]);
                        TR.CharacterFormat.Bold = true;
                    }

                    //Data Row
                    model.JobHistory = model.JobHistory.OrderBy(x => x.StartDT).ToList();
                    for (int r = 0; r < model.JobHistory.Count; r++)
                    {
                        TableRow DataRow = table.Rows[r + 1];
                        string[] data    = new string[] { (r + 1).ToString(), model.JobHistory[r].CompanyName, model.JobHistory[r].JobTitle, (model.JobHistory[r].StartDT.HasValue ? model.JobHistory[r].StartDT.Value.ToShortDateString() : ""), (model.JobHistory[r].EndDT.HasValue ? model.JobHistory[r].EndDT.Value.ToShortDateString() : "") };

                        //Columns.
                        for (int c = 0; c < data.Length; c++)
                        {
                            //Cell Alignment
                            DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                            //Fill Data in Rows
                            Spire.Doc.Documents.Paragraph p2 = DataRow.Cells[c].AddParagraph();
                            TextRange TR2 = p2.AppendText(data[c]);

                            //Format Cells
                            p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
                        }
                    }

                    //Replace text with Table
                    TextSelection selectionTable = document.FindString("{$JobHistory$}", true, true);
                    TextRange     rangeTable     = selectionTable.GetAsOneRange();
                    Spire.Doc.Documents.Paragraph paragraphTable = rangeTable.OwnerParagraph;
                    Body body  = paragraphTable.OwnerTextBody;
                    int  index = body.ChildObjects.IndexOf(paragraphTable);
                    body.ChildObjects.Remove(paragraphTable);
                    body.ChildObjects.Insert(index, table);
                }

                #endregion

                #region 套用樣式

                //套用文章段落樣式
                for (int s = 0; s < document.Sections.Count; s++)
                {
                    Spire.Doc.Section section = document.Sections[s];
                    //套用文章段落樣式
                    for (int p = 0; p < section.Paragraphs.Count; p++)
                    {
                        Spire.Doc.Documents.Paragraph pgh = section.Paragraphs[p];
                        pgh.ApplyStyle("Basic");
                        pgh.Format.BeforeSpacing = 12;
                    }

                    //套用表格樣式
                    for (int t = 0; t < document.Sections[s].Tables.Count; t++)
                    {
                        Spire.Doc.Table table = (Spire.Doc.Table)document.Sections[s].Tables[t];
                        table.PreferredWidth            = new PreferredWidth(WidthType.Percentage, 100);
                        table.TableFormat.IsAutoResized = true;

                        //set table border
                        //table.TableFormat.Borders.Right.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Left.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Top.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Horizontal.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Vertical.BorderType = Spire.Doc.Documents.BorderStyle.Thick;

                        for (int tr = 0; tr < table.Rows.Count; tr++)
                        {
                            for (int td = 0; td < table.Rows[tr].Cells.Count; td++)
                            {
                                for (int t_ph = 0; t_ph < table.Rows[tr].Cells[td].Paragraphs.Count; t_ph++)
                                {
                                    table.Rows[tr].Cells[td].Paragraphs[t_ph].ApplyStyle("Basic");
                                }
                            }
                        }
                    }
                }

                #endregion

                //匯出
                document.SaveToStream(ms, FileFormat.Docx);
            }
            catch (Exception ex)
            {
                result = false;
                msg    = ex.Message;
            }

            if (result)
            {
                return(ms.ToArray());
            }
            else
            {
                return(null);
            }
        }
        public IActionResult yjExportInfo(AddressRequestPayload payload)
        {
            var response = ResponseModelFactory.CreateInstance;

            string       sWebRootFolder = _hostingEnvironment.WebRootPath + "\\UploadFiles\\ImportUserInfoWord\\";
            var          timeInfo       = DateTime.Now.ToString("yyyyMMddHHmmss");
            var          wordName       = timeInfo + "address.docx";
            string       wordUrl        = sWebRootFolder + wordName;
            MemoryStream ms             = new MemoryStream();
            XWPFDocument m_Docx         = new XWPFDocument();

            m_Docx.Write(ms);
            ms.Flush();
            SaveToFile(ms, wordUrl);

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

            using (_dbContext)
            {
                Document document111 = new Document();
                document111.LoadFromFile(wordUrl);
                Section section = document111.Sections[0];
                section.Paragraphs[0].AppendBookmarkStart("picture");
                section.Paragraphs[0].AppendBookmarkEnd("picture");

                var      user = AuthContextService.CurrentUser;
                string   s1   = payload.Kw2;
                string[] s2   = s1.Split(" ");
                StringBuilder where = new StringBuilder();
                StringBuilder sql = new StringBuilder("SELECT * FROM HomeAddress HA ");
                for (int i = 0; i < s2.Length; i++)
                {
                    if (s2.Length > 0 && i == 0)
                    {
                        where.Append("WHERE ");
                    }
                    where.Append("HA.Address LIKE '%" + s2[i] + "%' ");
                    if (i >= 0 && i < s2.Length - 1)
                    {
                        where.Append(" AND ");
                    }
                }
                sql.Append(where);
                //var query = _dbContext.HomeAdd.FromSql(sql.ToString());
                var query = _dbContext.HomeAddress.FromSqlRaw(sql.ToString());
                if (!string.IsNullOrEmpty(payload.Kw))
                {
                    query = query.Where(x => x.Address.ToString().Contains(payload.Kw));
                }
                if (!string.IsNullOrEmpty(payload.Kw1))
                {
                    query = query.Where(x => x.Address.ToString().Contains(payload.Kw1));
                }
                var entities = query.ToList();
                //var entities = _dbContext.HomeAddress.Where(x => ids.IndexOf(x.HomeAddressUuid.ToString()) >= 0).ToList();
                for (int i = 0; i < entities.Count(); i++)
                {
                    var pata = _hostingEnvironment.WebRootPath + EWM.GetEWM2("h_" + entities[i].HomeAddressUuid.ToString(), _hostingEnvironment, entities[i].Address);
                    //实例化BookmarksNavigator类,指定需要添加图片的书签“”
                    BookmarksNavigator bn = new BookmarksNavigator(document111);
                    bn.MoveToBookmark("picture", true, true);
                    //添加段落,加载图片并插入到段落
                    Section section0 = document111.AddSection();
                    Spire.Doc.Documents.Paragraph paragraph = section0.AddParagraph();
                    Image      image   = Image.FromFile(pata);
                    DocPicture picture = document111.Sections[0].Paragraphs[0].AppendPicture(image);
                    picture.Width  = 160;
                    picture.Height = 180;
                    //picture.HorizontalPosition = 100.0f;
                    //picture.VerticalPosition = 50.0f;
                    bn.InsertParagraph(paragraph);
                    document111.Sections.Remove(section0);
                    //string output = sWebRootFolder + "test.docx";
                    document111.SaveToFile(wordUrl, FileFormat.Docx);
                    //Arraypata = pata.;
                    //list.Add(pata);
                }
                list.Add(wordUrl);
                //关闭进程
                document111.Dispose();
                var time  = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                var check = ZIP.CompressMulti(list, _hostingEnvironment.WebRootPath + "\\UploadFiles\\EWM\\" + time, false);
                if (check)
                {
                    response.SetSuccess("导出成功");
                    response.SetData("\\UploadFiles\\EWM\\" + time + ".zip");
                }
                else
                {
                    response.SetFailed("导出失败");
                }
            }
            return(Ok(response));
        }
예제 #14
0
 internal PageSetup(Section A_0) : base(A_0.Document, A_0)
 {
     this.borders_0 = new Spire.Doc.Documents.Borders();
 }