Пример #1
0
        public void pdf(String wordpath, String pdf)
        {
            // Wordを取り扱うための変数を定義する
            // ※ExcelやPowerPointも同じようなクラス名なので明示的に名前空間を書くことにする
            Microsoft.Office.Interop.Word.Application objWord      = null;
            Microsoft.Office.Interop.Word.Documents   objDocuments = null;
            Microsoft.Office.Interop.Word.Document    objDocument  = null;
            // ファイル名を定義する
            string strWordFilePath = string.Empty;
            string strPdfFilePath  = pdf;

            try
            {
                // ファイルパスを初期化する
                // ※今回PDFはWord文章と同じ場所に拡張子だけ変えて保存するようにした
                strWordFilePath = wordpath;
                // strPdfFilePath = System.IO.Path.GetDirectoryName(strWordFilePath) + @"\" + System.IO.Path.GetFileNameWithoutExtension(strWordFilePath) + @".pdf";
                // Wordオブジェクトを実体化する
                objWord = new Microsoft.Office.Interop.Word.Application();
                // 文章を管理しているオブジェクトを取得する
                objDocuments = objWord.Documents;
                // PDFに変換するWord文章を開く
                objDocument = objDocuments.Open(strWordFilePath);
                // PDF形式で保存する
                objDocument.ExportAsFixedFormat(strPdfFilePath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
            }
            catch (System.Exception objException)
            {
                System.Console.WriteLine(objException.Message);
            }
            finally
            {
                // 例外が発生しても必ずWordの文章を閉じるように処理はここ
                if (objDocument != null)
                {
                    objDocument.Close();
                }
                // 例外が発生しても必ずWordを狩猟するように処理はここ
                if (objWord != null)
                {
                    objWord.Quit();
                }
            }
        }
        /// <summary>
        /// 导出Word 的方法
        /// </summary>
        private void tslExport_Word()
        {
            SaveFileDialog sfile = new SaveFileDialog();

            sfile.AddExtension = true;
            sfile.DefaultExt   = ".doc";
            sfile.Filter       = "(*.doc)|*.doc";
            sfile.FileName     = "理文检测系统退货还包统计Word报表" + DateTime.Now.ToShortDateString();
            if (sfile.ShowDialog() == DialogResult.OK)
            {
                object path = sfile.FileName;
                Object none = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Application wordApp  = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
                //建立表格
                Microsoft.Office.Interop.Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, dgvCarStatisticsQC.Rows.Count + 1, dgvCarStatisticsQC.Columns.Count, ref none, ref none);
                try
                {
                    for (int i = 0; i < dgvCarStatisticsQC.Columns.Count; i++)//设置标题
                    {
                        table.Cell(0, i + 1).Range.Text = dgvCarStatisticsQC.Columns[i].HeaderText;
                    }
                    for (int i = 1; i < dgvCarStatisticsQC.Rows.Count; i++)//填充数据
                    {
                        for (int j = 0; j < dgvCarStatisticsQC.Columns.Count; j++)
                        {
                            //table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                            if (dgvCarStatisticsQC[j, i - 1].Value != null)
                            {
                                table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                            }
                        }
                    }
                    document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
                    document.Close(ref none, ref none, ref none);
                    MessageBox.Show("导出数据成功!");
                }

                finally
                {
                    wordApp.Quit(ref none, ref none, ref none);
                }
            }
        }
Пример #3
0
        public void opendoc(string fn)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss     = System.Reflection.Missing.Value;
            object path     = fn;
            object readOnly = true;

            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);

            for (int p = 0; p < docs.Paragraphs.Count; p++)
            {
                inputTextBox.Text += docs.Paragraphs[p + 1].Range.Text.ToString();
            }
            docs.Close();
            word.Quit();


            //  MessageBox.Show("DOC file is opened");
        }
Пример #4
0
        //Pega todas as linhas até encontrar outro titulo igual
        public string DocReaderGetAllUntilTitle(string fileLocation, string headingText)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss     = System.Reflection.Missing.Value;
            object path     = fileLocation;
            object readOnly = true;

            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
            string totaltext = "";
            int    ind       = 0;
            int    paraCount = docs.Paragraphs.Count;

            for (int i = 1; i < paraCount; i++)
            {
                if (docs.Paragraphs[i].Range.Text.ToString().TrimEnd('\r').ToUpper() != headingText.ToUpper())
                {
                    totaltext += " \r\n " + docs.Paragraphs[i].Range.Text.ToString();
                }
                else if (docs.Paragraphs[i].Range.Text.ToString().TrimEnd('\r').ToUpper() == headingText.ToUpper() && ind > 0)
                {
                    break;
                }
                else
                {
                    ind++;
                }
            }

            if (totaltext == "")
            {
                totaltext = "No such data found!";
            }

            docs.Close();
            word.Quit();

            return(totaltext);
        }
Пример #5
0
        private void LoadSpeakersFromDocFile(object path)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss     = System.Reflection.Missing.Value;
            object readOnly = false;

            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
            docs.ActiveWindow.Selection.WholeStory();
            docs.ActiveWindow.Selection.Copy();
            IDataObject data = Clipboard.GetDataObject();

            string[] textLines = data.GetData(DataFormats.Text).ToString().Split('\r');
            for (int i = 0; i < textLines.Length; ++i)
            {
                if (textLines[i] != "\n")
                {
                    GetSpeakerFromTextLine(textLines[i]);
                }
            }
            docs.Close(ref miss, ref miss, ref miss);
            word.Quit(ref miss, ref miss, ref miss);
            UpdateSpeakersGrid(currentSpeakersId - 1);
        }
Пример #6
0
        private void button3_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application ObjWord = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    Doc     = ObjWord.Documents.Add(dir + "\\Prilozhenie4.docx");
            Doc.Bookmarks["Name"].Range.Text           = textBox2.Text + " " + textBox3.Text + " " + textBox4.Text;
            Doc.Bookmarks["Date_of_Birth"].Range.Text  = ", " + textBox5.Text + " г.";
            Doc.Bookmarks["Seriya"].Range.Text         = textBox6.Text;
            Doc.Bookmarks["Number"].Range.Text         = textBox7.Text;
            Doc.Bookmarks["Type"].Range.Text           = textBox8.Text;
            Doc.Bookmarks["Learning_year"].Range.Text  = textBox9.Text;
            Doc.Bookmarks["City"].Range.Text           = textBox10.Text;
            Doc.Bookmarks["Srok"].Range.Text           = textBox11.Text;
            Doc.Bookmarks["Begin_Learning"].Range.Text = textBox12.Text;
            Doc.Bookmarks["End_Learning"].Range.Text   = textBox13.Text;
            Doc.Bookmarks["Rector"].Range.Text         = comboBox1.Text;
            Doc.Bookmarks["Name2"].Range.Text          = comboBox2.Text;
            Doc.Bookmarks["Director"].Range.Text       = comboBox3.Text;
            Doc.Bookmarks["Name3"].Range.Text          = comboBox4.Text;

            Doc.SaveAs(FileName: dir1 + "\\" + textBox2.Text + "_" + textBox3.Text + "_For_print.docx");
            Doc.Close();
            ObjWord.Quit();
        }
Пример #7
0
        public bool WordToPdf(object sourcePath, string targetPath)
        {
            bool           result            = false;
            WdExportFormat wdExportFormatPDF = WdExportFormat.wdExportFormatPDF;
            object         missing           = Type.Missing;

            Microsoft.Office.Interop.Word.ApplicationClass applicationClass = null;
            Microsoft.Office.Interop.Word.Document         document         = null;
            try
            {
                applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass();
                document         = applicationClass.Documents.Open(ref sourcePath, 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);
                if (document != null)
                {
                    document.ExportAsFixedFormat(targetPath, wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateWordBookmarks, true, true, false, ref missing);
                }
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (document != null)
                {
                    document.Close(ref missing, ref missing, ref missing);
                    document = null;
                }
                if (applicationClass != null)
                {
                    applicationClass.Quit(ref missing, ref missing, ref missing);
                    applicationClass = null;
                }
            }
            return(result);
        }
Пример #8
0
        public ActionResult Doc(HttpPostedFileBase file)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss     = System.Reflection.Missing.Value;
            var    fileName = Path.GetFileName(file.FileName);
            var    path     = Path.Combine(Server.MapPath("~/App_Data"), fileName);

            file.SaveAs(path);

            object filepath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
            object readOnly = true;

            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref filepath, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
            string totaltext = "";

            for (int i = 0; i < docs.Paragraphs.Count; i++)
            {
                totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
            }
            //Console.WriteLine(totaltext);
            docs.Close();
            word.Quit();
            return(View("Index"));
        }
Пример #9
0
        public void ExportFile(string strFileTemplate, SortedList <string, string> lstKeyAndValueReplaces, Boolean isVisible = false, string strFileNameDefault = "")
        {
            //Lưu file vào vị trí nào
            string         strFilePath = "";
            SaveFileDialog saveDlg     = new SaveFileDialog();

            saveDlg.Filter           = "Word 2003 file(*.doc)|*.doc | Word 2007 file(*.docx)|*.docx";
            saveDlg.AddExtension     = true;
            saveDlg.RestoreDirectory = true;
            saveDlg.Title            = "Chọn vị trí lưu file?";

            //Tên file
            if (!string.IsNullOrEmpty(strFileNameDefault))
            {
                saveDlg.FileName = string.Format(@"{0}", strFileNameDefault);
            }

            if (saveDlg.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            Word.Application wordApp = new Word.Application();
            Microsoft.Office.Interop.Word.Document newDocument = wordApp.Documents.Open(strFileTemplate);

            try
            {
                //Xoá file đã tồn tại, tại vị trí lưu
                strFilePath = saveDlg.FileName;
                if (File.Exists(strFilePath))
                {
                    File.Delete(strFilePath);
                }


                //Replace key = giá trị
                foreach (string keys in lstKeyAndValueReplaces.Keys)
                {
                    while (newDocument.Content.Find.Execute(FindText: keys))
                    {
                        if (newDocument.Content.Find.Execute(FindText: keys))
                        {
                            if (lstKeyAndValueReplaces[keys].Length > 254)
                            {
                                if (newDocument.Application.Selection.Find.Execute(keys) == true)
                                {
                                    newDocument.Application.Selection.Text = lstKeyAndValueReplaces[keys];
                                    break;
                                }
                            }
                            else
                            {
                                newDocument.Content.Find.Execute(FindText: keys, ReplaceWith: lstKeyAndValueReplaces[keys], Replace: WdReplace.wdReplaceOne);
                            }
                        }
                    }
                }

                CreateDocumentPropertyTable(newDocument);
                //Lưu file
                newDocument.SaveAs(strFilePath);

                wordApp.Visible = isVisible;

                if (!isVisible)
                {
                    newDocument.Close();
                    wordApp.Quit();
                }
            }
            catch (Exception ex)
            {
                newDocument.Close();
                wordApp.Quit();
                MessageBox.Show(ex.Message);
            }
        }
Пример #10
0
        private void button1_Click(object sender, EventArgs e)
        {
            ///////////////////////////////////////////////////////////// WAR ZONE
            ////////////////////////////////////////////////////////////
            CountryOfWorking.Add(4, "Republiki Czeskiej");
            CountryOfWorking.Add(5, "Słowacja");
            CountryOfWorking.Add(6, "Belgii");

            Countries.Add(1, "Czech Republic");
            Countries.Add(2, "Slovakia");
            Countries.Add(3, "Belgie");

            DocumentType.Add(1, "BIOPASSPORT");
            DocumentType.Add(2, "VIZA");
            // тут будут 3 шаблона CZ -SMLOUVA- PL -UMOVA- -ANEX-

            //  C:\\Users\\Dell\\Documents\\!!!Некит\\Form.xlsx

            object templateForCzSmlouva = filePath + "\\Templates\\HellOfADrug\\smlouva.docx";
            object templateForPlUmova   = filePath + "\\Templates\\HellOfADrug\\umowa.docx";
            object templateForPlAneks   = filePath + "\\Templates\\HellOfADrug\\AneksPl.docx";
            object templateForCestjak   = filePath + "\\Templates\\HellOfADrug\\CESTAK.docx";

            ////-----------Бельгийские шаблоны-----------////
            object templateForBelSmlouva   = filePath + "\\Templates\\HellOfADrug\\nlUmowa.docx";
            object templateForBelSmlouvaPl = filePath + "\\Templates\\HellOfADrug\\nlUmowaPl.docx";

            string connectionString = ConfigurationManager.ConnectionStrings["LEGAL.Properties.Settings.WorkDBFirstTryConnectionString"].ConnectionString; //строка подключения

            int maxNumbWorkers = countPeopleInExcelFile() - 1;

            string[] ztmp = new string[15];
            string[] arrForPlCompanyInformation = new string[8];

            for (int i = 0; i < maxNumbWorkers; i++)
            {
                ztmp = readExcel(i);

                if (ztmp[6] == "PORTOFINO SP.Z O.O" || ztmp[6] == "VENEZIA SP.Z O.O" || ztmp[6] == "AGRAT SP.Z O.O" || ztmp[6] == "POLFIZ SP.Z O.O" || AllMethods.checkSpaceInFolderName(ztmp[1]) || ztmp[7] != null)
                {
                    SqlConnection connection = new SqlConnection(connectionString);
                    //SqlConnection connect = conn.OpenSqlConn(connectionString);
                    string sqlExpressionForFindingCz = "SELECT CompanyName, CompanyAdress, CompanyRegion, CompanyKRS, CompanyNIP, CompanyRepresentant, CertifikatNumber, CertifikatDate FROM CompaniesPL where CompanyName = (N'" + ztmp[6] + "')";

                    // vot tu oshibka byla connection.ConnectionString = connectionString;
                    connection.Open();
                    SqlCommand CommandForToGetAllInfAboutPlCompany = new SqlCommand(sqlExpressionForFindingCz, connection);

                    SqlDataReader ReaderReadDataFromCommandForGettingAllInformationForPlCompany = CommandForToGetAllInfAboutPlCompany.ExecuteReader();

                    while (ReaderReadDataFromCommandForGettingAllInformationForPlCompany.Read())
                    {
                        arrForPlCompanyInformation[0] = Convert.ToString(ReaderReadDataFromCommandForGettingAllInformationForPlCompany.GetValue(0));
                        arrForPlCompanyInformation[1] = Convert.ToString(ReaderReadDataFromCommandForGettingAllInformationForPlCompany.GetValue(1));
                        arrForPlCompanyInformation[2] = Convert.ToString(ReaderReadDataFromCommandForGettingAllInformationForPlCompany.GetValue(2));
                        arrForPlCompanyInformation[3] = Convert.ToString(ReaderReadDataFromCommandForGettingAllInformationForPlCompany.GetValue(3));
                        arrForPlCompanyInformation[4] = Convert.ToString(ReaderReadDataFromCommandForGettingAllInformationForPlCompany.GetValue(4));
                        arrForPlCompanyInformation[5] = Convert.ToString(ReaderReadDataFromCommandForGettingAllInformationForPlCompany.GetValue(5));
                        // arrForPlCompanyInformation[6] = Convert.ToString(ReaderReadDataFromCommandForGettingAllInformationForPlCompany.GetValue(6));
                        string ll   = Convert.ToString(ReaderReadDataFromCommandForGettingAllInformationForPlCompany.GetValue(6));
                        int    cont = int.Parse(ll.Replace(" ", string.Empty));
                        arrForPlCompanyInformation[6] = Convert.ToString(cont);
                        DateTime date = new DateTime();
                        date = Convert.ToDateTime(ReaderReadDataFromCommandForGettingAllInformationForPlCompany.GetValue(7));
                        arrForPlCompanyInformation[7] = date.ToString("dd/MM/yyyy");
                        // arrForPlCompanyInformation[7] = Convert.ToString(ReaderReadDataFromCommandForGettingAllInformationForPlCompany.GetValue(7));
                        // string date = DateTime.Now.ToString("Myyyy");
                    }
                    ReaderReadDataFromCommandForGettingAllInformationForPlCompany.Close();
                    connection.Close();

                    if (ztmp[5] == null)
                    {
                        //connection = conn.OpenSqlConn(connectionString);


                        SqlConnection connectionTwo = new SqlConnection();
                        string        SqlExpressionForFindingAddressIfItsNull = "Select CompanyAddress from CompanyCustomers where CompanyName = @test"; //  "(N'" + ztmp[4] + "')";
                        connectionTwo.ConnectionString = connectionString;
                        connectionTwo.Open();
                        SqlCommand CommandToGetAdress = new SqlCommand(SqlExpressionForFindingAddressIfItsNull, connectionTwo);
                        CommandToGetAdress.Parameters.AddWithValue("@test", ztmp[4]);
                        SqlDataReader ReaderReadDataFromCommandForGettingPlAdress = CommandToGetAdress.ExecuteReader();

                        while (ReaderReadDataFromCommandForGettingPlAdress.Read())
                        {
                            ztmp[5] = Convert.ToString(ReaderReadDataFromCommandForGettingPlAdress.GetValue(0));
                        }
                        ReaderReadDataFromCommandForGettingPlAdress.Close();
                        connectionTwo.Close();
                        //conn.CloseSqlConn(connection);
                    }

                    if (ztmp[8] == "" || ztmp[8] == null)
                    {
                        SqlConnection ConnectionForFindingPaymentPerHour    = new SqlConnection();
                        string        SQlExpressionForFindingPaymentPerHour = "select Salary FROM Professions where Professions.CZ = (N'" + ztmp[7] + "')";
                        ConnectionForFindingPaymentPerHour.ConnectionString = connectionString;
                        ConnectionForFindingPaymentPerHour.Open();
                        SqlCommand CommandToGetHours = new SqlCommand(SQlExpressionForFindingPaymentPerHour, ConnectionForFindingPaymentPerHour);

                        SqlDataReader reader = CommandToGetHours.ExecuteReader();

                        while (reader.Read())
                        {
                            ztmp[8] = Convert.ToString(reader.GetValue(0));
                        }
                        reader.Close();
                        ConnectionForFindingPaymentPerHour.Close();
                    }

                    if (ztmp[9] == "" || ztmp[9] == null)
                    {
                        SqlConnection ConnectionForPlProffesion = new SqlConnection();
                        string        SqlExpresseonForFindingProffesionInPolish = "select Pl FROM Professions where Professions.CZ = (N'" + ztmp[7] + "')";
                        ConnectionForPlProffesion.ConnectionString = connectionString;
                        ConnectionForPlProffesion.Open();

                        SqlCommand CommandGetPlProffesion = new SqlCommand(SqlExpresseonForFindingProffesionInPolish, ConnectionForPlProffesion);

                        SqlDataReader redaderTwo = CommandGetPlProffesion.ExecuteReader();
                        while (redaderTwo.Read())
                        {
                            ztmp[9] = Convert.ToString(redaderTwo.GetValue(0));
                        }

                        redaderTwo.Close();
                        ConnectionForPlProffesion.Close();
                    }

                    if (ztmp[10] == "" || ztmp[10] == null)
                    {
                        ztmp[10] = DateTime.Now.ToString("dd/M/yyyy");
                    }

                    if (ztmp[11] == "" || ztmp[11] == null)
                    {
                        SqlConnection ConnectionForFindingPlProffesionInCaps        = new SqlConnection();
                        string        SqlExpressionDorFindingProffesionInPolishCaps = "select Pl FROM Professions where Professions.CZ = (N'" + ztmp[7] + "')";
                        ConnectionForFindingPlProffesionInCaps.ConnectionString = connectionString;
                        ConnectionForFindingPlProffesionInCaps.Open();

                        SqlCommand CommandGetPlProfInCaps = new SqlCommand(SqlExpressionDorFindingProffesionInPolishCaps, ConnectionForFindingPlProffesionInCaps);

                        SqlDataReader redaderTwo = CommandGetPlProfInCaps.ExecuteReader();
                        while (redaderTwo.Read())
                        {
                            string jonh = Convert.ToString(redaderTwo.GetValue(0));

                            ztmp[11] = jonh.ToUpper();
                        }

                        redaderTwo.Close();
                        ConnectionForFindingPlProffesionInCaps.Close();
                    }

                    ztmp[14] = "zagluskaEsliPusto";

                    if (checkCountry(ztmp[4]) == Countries[3])
                    {
                        string        NlProffession;
                        SqlConnection ConnectionForFindingNlProffession             = new SqlConnection();
                        string        SqlExpressionDorFindingProffesionInPolishCaps = "select Nl FROM Professions where Professions.Cz = (N'" + ztmp[7] + "')";
                        ConnectionForFindingNlProffession.ConnectionString = connectionString;
                        ConnectionForFindingNlProffession.Open();
                        SqlCommand CommandToGetNlProffession     = new SqlCommand(SqlExpressionDorFindingProffesionInPolishCaps, ConnectionForFindingNlProffession);
                        object     ObjectForGettingNlProffession = CommandToGetNlProffession.ExecuteScalar();
                        NlProffession = ObjectForGettingNlProffession.ToString();

                        ztmp[14] = NlProffession;
                    }



                    ///////начинаем вставлять, шаблоны их три штуки
                    ///
                    if (!checkBox1.Checked)
                    {
                        if (checkCountry(ztmp[4]) == Countries[3])
                        {
                            TakeDataFromExcelPutItToWord(ztmp, arrForPlCompanyInformation, templateForBelSmlouva);
                            TakeDataFromExcelPutItToWord(ztmp, arrForPlCompanyInformation, templateForBelSmlouvaPl);
                            TakeDataFromExcelPutItToWord(ztmp, arrForPlCompanyInformation, templateForPlAneks);
                            TakeDataFromExcelPutItToWord(ztmp, arrForPlCompanyInformation, templateForCestjak);
                        }
                        else
                        {
                            TakeDataFromExcelPutItToWord(ztmp, arrForPlCompanyInformation, templateForCzSmlouva);
                            TakeDataFromExcelPutItToWord(ztmp, arrForPlCompanyInformation, templateForPlUmova);
                            TakeDataFromExcelPutItToWord(ztmp, arrForPlCompanyInformation, templateForPlAneks);
                            TakeDataFromExcelPutItToWord(ztmp, arrForPlCompanyInformation, templateForCestjak);
                        }
                    }
                    else
                    {
                        TakeDataFromExcelPutItToWord(ztmp, arrForPlCompanyInformation, templateForCestjak);
                    }
                }
                else
                {
                    MessageBox.Show("Проверь PL название фирмы и только один пробел должен быть между именем и фамилией.");
                    break;
                }
            }

            void TakeDataFromExcelPutItToWord(string[] CompanyHeadData, string[] WorkerData, object template)  // функция получает массив с данными и вставляет в три шаблона
            {
                Microsoft.Office.Interop.Word.Application appMy = new Microsoft.Office.Interop.Word.Application();


                Microsoft.Office.Interop.Word.Document docMy = null;

                object missingMy = Type.Missing;

                docMy = appMy.Documents.Open(template, missingMy, missingMy);
                appMy.Selection.Find.ClearFormatting();
                appMy.Selection.Find.Replacement.ClearFormatting();

                int xxx = CompanyHeadData.Length + WorkerData.Length; //длина общего массива в котором храним два других массива, первый массив с данными из эксель второй данные по фирме их дб, и третий БУДЕТ с данными по Цестяку

                string[] tmpForData = new string[xxx];

                for (int z = 0; z < CompanyHeadData.Length; z++)
                {
                    tmpForData[z] = CompanyHeadData[z];
                }

                for (int k = 0; k < WorkerData.Length; k++)
                {
                    tmpForData[k + CompanyHeadData.Length] = WorkerData[k];
                }
                string date = DateTime.Now.ToString("Myyyy");

                string readNumber()
                {
                    string text      = File.ReadAllText(filePath + "\\Templates\\docNumb.txt", Encoding.Default);
                    int    newNumber = Convert.ToInt32(text) + 1;
                    string newText   = Convert.ToString(newNumber);

                    File.WriteAllText(filePath + "\\Templates\\docNumb.txt", newText);

                    return(newText);
                }

                appMy.Selection.Find.Execute("<zzz>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[0], 2);
                appMy.Selection.Find.Execute("<surname>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[1], 2);
                appMy.Selection.Find.Execute("<dateOfBirth>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[2], 2);
                appMy.Selection.Find.Execute("<passNumber>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[3], 2);
                appMy.Selection.Find.Execute("<companyCz>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[4], 2);
                appMy.Selection.Find.Execute("<companyCzAddress>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[5], 2);
                appMy.Selection.Find.Execute("<PlCompanyNameIfFull>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[6], 2);
                appMy.Selection.Find.Execute("<employmentCz>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[7], 2);
                //appMy.Selection.Find.Execute("<hoursPerMounth>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[8], 2);
                appMy.Selection.Find.Execute("<employmentPL>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[9], 2);
                //appMy.Selection.Find.Execute("<AddressOfLivingDontUSe>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[10], 2);
                appMy.Selection.Find.Execute("<dateOfStartWorkig>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[10], 2); //лишняя надо убрать
                appMy.Selection.Find.Execute("<workPlCestjak>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[11], 2);
                appMy.Selection.Find.Execute("<PlCompanyName>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[15], 2);
                appMy.Selection.Find.Execute("<PlCompanyAddress>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[16], 2);
                appMy.Selection.Find.Execute("<REGON>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[17], 2);
                appMy.Selection.Find.Execute("<KRS>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[18], 2);
                appMy.Selection.Find.Execute("<NIP>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[19], 2);
                appMy.Selection.Find.Execute("<Representant>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[20], 2);      // + отсюда дописываю сегодняшнее инфо
                appMy.Selection.Find.Execute("<CertifikateNumber>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[21], 2); // + отсюда дописываю сегодняшнее инфо
                appMy.Selection.Find.Execute("<CertifikateDate>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[22], 2);   // + отсюда дописываю сегодняшнее инфо
                appMy.Selection.Find.Execute("<employmentNl>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[14], 2);      // + отсюда дописываю сегодняшнее инфо


                if (checkCountry(tmpForData[4]) == Countries[1])
                {
                    appMy.Selection.Find.Execute("<CountryOfWorking>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, Convert.ToString(CountryOfWorking[4]), 2);
                }
                else if (checkCountry(tmpForData[4]) == Countries[2])
                {
                    appMy.Selection.Find.Execute("<CountryOfWorking>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, Convert.ToString(CountryOfWorking[5]), 2);
                }
                else if (checkCountry(tmpForData[4]) == Countries[3])
                {
                    appMy.Selection.Find.Execute("<CountryOfWorking>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, Convert.ToString(CountryOfWorking[6]), 2);
                }


                if (checkCountry(tmpForData[4]) == Countries[1] || checkCountry(tmpForData[4]) == Countries[2])
                {
                    appMy.Selection.Find.Execute("<hoursPerMounth>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, Convert.ToDouble(tmpForData[8]), 2);
                }
                else if (checkCountry(tmpForData[4]) == Countries[3])
                {
                    appMy.Selection.Find.Execute("<hoursPerMounth>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, "59", 2);
                }

                if (ztmp[13] == "" || ztmp[13] == null)
                {
                    appMy.Selection.Find.Execute("<dateOfStartWorkigPlusTwoY>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, AllMethods.bhBjj(tmpForData[10]), 2);
                }
                else
                {
                    appMy.Selection.Find.Execute("<dateOfStartWorkigPlusTwoY>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, tmpForData[13], 2);
                }


                appMy.Selection.Find.Execute("<IdDate>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, readNumber(), 2);
                appMy.Selection.Find.Execute("<cestNumber>", missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, missingMy, date, 2);

                Random jj = new Random();

                string zzz = Convert.ToString(jj.Next(1, 1000));

                if (!checkBox1.Checked)
                {
                    if (!Directory.Exists(filePath + "\\Fresh L\\" + tmpForData[1] + "_" + tmpForData[3])) // проверяем если есть папка, чисто по логике не должно быть, по-этому сразу можно сохранять туда smlovuCZ
                    {
                        //создаем папку и сразу сохраняем

                        string        PathForFolder    = filePath + "\\Fresh L\\" + tmpForData[1] + "_" + tmpForData[3];
                        string        nlNameForSmlouva = "\\SmlouvaNL";
                        string        plNameForSmlouva = "\\SmlouvaCZ";
                        DirectoryInfo DirInfo          = new DirectoryInfo(PathForFolder);
                        DirInfo.Create();


                        object FilePathForFakturaNL = (object)PathForFolder + nlNameForSmlouva + tmpForData[15] + ".docx";
                        object FilePathForFakturaPL = (object)PathForFolder + plNameForSmlouva + tmpForData[15] + ".docx";


                        if (checkCountry(ztmp[4]) == Countries[3])
                        {
                            docMy.SaveAs2(FilePathForFakturaNL, missingMy, missingMy, missingMy);

                            //MessageBox.Show("Files Are Created!");
                            docMy.Close(false, missingMy, missingMy);
                            appMy.Quit(false, false, false);
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(appMy);
                        }
                        else
                        {
                            docMy.SaveAs2(FilePathForFakturaPL, missingMy, missingMy, missingMy);

                            //MessageBox.Show("Files Are Created!");
                            docMy.Close(false, missingMy, missingMy);
                            appMy.Quit(false, false, false);
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(appMy);
                        }
                    }
                    else
                    {
                        //папка есть значит просто сохранеем в уже созданную папку

                        //проверяю уже существует файл контракта если файла контракта нет то
                        if (!File.Exists(filePath + "\\Fresh L\\" + tmpForData[1] + "_" + tmpForData[3] + "\\UmovaPL" + tmpForData[15] + ".docx"))
                        {
                            object FilePathForFaktura = (object)filePath + "\\Fresh L\\" + tmpForData[1] + "_" + tmpForData[3] + "\\UmovaPL" + tmpForData[15] + ".docx";

                            docMy.SaveAs2(FilePathForFaktura, missingMy, missingMy, missingMy);

                            //MessageBox.Show("Files Are Created!");
                            docMy.Close(false, missingMy, missingMy);
                            appMy.Quit(false, false, false);
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(appMy);
                        }
                        else
                        {
                            if (!File.Exists(filePath + "\\Fresh L\\" + tmpForData[1] + "_" + tmpForData[3] + "\\AnexPl" + tmpForData[15] + ".docx"))
                            {
                                object FilePathForFaktura = (object)filePath + "\\Fresh L\\" + tmpForData[1] + "_" + tmpForData[3] + "\\AnexPl" + tmpForData[15] + ".docx";

                                docMy.SaveAs2(FilePathForFaktura, missingMy, missingMy, missingMy);

                                //MessageBox.Show("Files Are Created!");
                                docMy.Close(false, missingMy, missingMy);
                                appMy.Quit(false, false, false);
                                System.Runtime.InteropServices.Marshal.ReleaseComObject(appMy);
                            }
                            else
                            {
                                object FilePathForFaktura = (object)filePath + "\\Fresh L\\" + tmpForData[1] + "_" + tmpForData[3] + "\\CESTAK" + tmpForData[15] + "_" + tmpForData[3] + ".docx";

                                docMy.SaveAs2(FilePathForFaktura, missingMy, missingMy, missingMy);

                                //MessageBox.Show("Files Are Created!");
                                docMy.Close(false, missingMy, missingMy);
                                appMy.Quit(false, false, false);
                                System.Runtime.InteropServices.Marshal.ReleaseComObject(appMy);
                            }
                        } if (!File.Exists(filePath + "\\Fresh L\\" + tmpForData[1] + "_" + tmpForData[3] + "\\CESTAK" + tmpForData[15] + "_" + tmpForData[3] + ".docx") || !File.Exists(filePath + "\\Fresh L\\" + tmpForData[1] + "_" + tmpForData[3] + "\\CESTAK" + tmpForData[15] + "_" + tmpForData[3] + ".docx"))
                        {
                            if (checkCountry(ztmp[4]) == Countries[1])
                            {
                                using (StreamWriter sw = File.CreateText(filePath + "\\Fresh L\\" + tmpForData[1] + "_" + tmpForData[3] + "\\" + tmpForData[1] + "_" + tmpForData[9] + "_" + tmpForData[8] + "zl_" + checkHours(ztmp[9]) + "_" + "hours_" + "_" + tmpForData[12] + "_" + tmpForData[13] + ".txt"))
                                {
                                    sw.WriteLine(tmpForData[1] + "_" + tmpForData[3] + "\\" + tmpForData[1] + "_" + tmpForData[9] + "_" + tmpForData[8] + "zl" + "_" + tmpForData[12] + tmpForData[13]);
                                }
                            }
                            else if (checkCountry(ztmp[4]) == Countries[3])
                            {
                                using (StreamWriter sw = File.CreateText(filePath + "\\Fresh L\\" + tmpForData[1] + "_" + tmpForData[3] + "\\" + tmpForData[1] + "_" + tmpForData[9] + "_" + "59zl" + "_" + "80" + "hours_" + tmpForData[12] + "_" + tmpForData[13] + ".txt"))
                                {
                                    sw.WriteLine(tmpForData[1] + "_" + tmpForData[3] + "\\" + tmpForData[1] + "_" + tmpForData[9] + "_" + "59zl" + "_" + tmpForData[12] + tmpForData[13]);
                                }
                            }
                        }
                    }
                }
                else
                {
                    string pathToFolder       = filePath + "\\Fresh L\\" + tmpForData[4]; // путь к папке с названием фирмы PL
                    object FilePathForFaktura = (object)filePath + "\\Fresh L\\" + tmpForData[4] + "\\" + tmpForData[1] + "_" + tmpForData[3] + "_CESTAK.docx";

                    if (!File.Exists(pathToFolder))
                    {
                        DirectoryInfo CreateDirectoryObject = new DirectoryInfo(pathToFolder);
                        CreateDirectoryObject.Create();
                        docMy.SaveAs2(FilePathForFaktura, missingMy, missingMy, missingMy);

                        //MessageBox.Show("Files Are Created!");
                        docMy.Close(false, missingMy, missingMy);
                        appMy.Quit(false, false, false);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(appMy);
                    }
                    else
                    {
                        docMy.SaveAs2(FilePathForFaktura, missingMy, missingMy, missingMy);
                        //MessageBox.Show("Files Are Created!");
                        docMy.Close(false, missingMy, missingMy);
                        appMy.Quit(false, false, false);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(appMy);
                    }
                }
            }

            MessageBox.Show("Files Are Created!");
        }
Пример #11
0
        //生成word文档
        public static void ExpWordByWord(int intStudentId)
        {
            Entity.Join_Student infoStudent = DAL.Join_Student.Join_StudentEntityGet(intStudentId);
            if (infoStudent == null)
            {
                return;
            }

            Entity.GaoKaoCard infoGaoKaoCard = DAL.GaoKaoCard.GaoKaoCardEntityGetByStudentId(intStudentId);
            if (infoGaoKaoCard == null)
            {
                return;
            }
            //文件路径和名称
            object fileName = System.Web.HttpContext.Current.Server.MapPath("~/") + "CePing/ImgOfResult/Ability/" + infoGaoKaoCard.KaHao + "(" + infoStudent.StudentName + "_" + intStudentId + ")" + "_职业能力测评.doc";//获取服务器路径

            //判定文件是否已经存在了
            if (Basic.Utils.FileExists(fileName.ToString()))
            {
                return;
            }

            #region 基本信息处理
            DataTable dt = DAL.Join_AbilityResults.Join_AbilityResultsList("UserId=" + intStudentId); //获取该学生的测试结果
            if (dt != null && dt.Rows.Count > 0)
            {
                string Language    = dt.Rows[0]["Language"].ToString();
                string Tissue      = dt.Rows[0]["Tissue"].ToString();
                string Among       = dt.Rows[0]["Among"].ToString();
                string Mathematics = dt.Rows[0]["Mathematics"].ToString();
                string Motion      = dt.Rows[0]["Motion"].ToString();
                string Writing     = dt.Rows[0]["Writing"].ToString();
                string Watch       = dt.Rows[0]["Watch"].ToString();
                string Space       = dt.Rows[0]["Space"].ToString();
                string Art         = dt.Rows[0]["Art"].ToString();
                //各能力得分
                intYanYu           = Basic.TypeConverter.StrToInt(Language);
                intShuLi           = Basic.TypeConverter.StrToInt(Tissue);
                intKongJianPanDuan = Basic.TypeConverter.StrToInt(Among);
                intChaJueXiJie     = Basic.TypeConverter.StrToInt(Mathematics);
                intShuXie          = Basic.TypeConverter.StrToInt(Motion);
                intYunDongXieTiao  = Basic.TypeConverter.StrToInt(Writing);
                intDongShou        = Basic.TypeConverter.StrToInt(Watch);
                intSheHuiJiaoWang  = Basic.TypeConverter.StrToInt(Space);
                intZuZhiGuanLi     = Basic.TypeConverter.StrToInt(Art);
            }
            else
            {
                return;
            }

            //创建数组,通过冒泡排序得到最大值和最小值
            list = new int[] { intYanYu, intShuLi, intKongJianPanDuan, intChaJueXiJie, intShuXie, intYunDongXieTiao, intDongShou, intSheHuiJiaoWang, intZuZhiGuanLi };
            DAL.Comm.BubbleSortUp(list);
            intMax = list[8]; //最大值
            intMin = list[0]; //最小值

            #endregion


            Word._Application app = new Word.Application();
            //表示System.Type信息中的缺少值
            object nothing = Type.Missing;
            try
            {
                //读取模板文件
                object temp = System.Web.HttpContext.Current.Server.MapPath("~/CePing/TempletOfAbility.doc");//读取模板文件
                //建立一个基于摸版的文档
                Word._Document doc = app.Documents.Add(ref temp, ref nothing, ref nothing, ref nothing);
                //
                #region 填充学生基本信息

                Word.Table tb1 = doc.Tables[1];
                if (tb1.Rows.Count == 4)
                {
                    GenerateWordDocument.BaseInfo(tb1, infoGaoKaoCard, infoStudent);
                }

                #endregion

                //
                #region 职业兴趣测评结果:各能力得分、评级
                Word.Table tb2 = doc.Tables[2];
                if (tb2.Rows.Count == 10)
                {
                    //在指定单元格填值
                    //第2行 言语能力
                    tb2.Cell(2, 2).Range.Text = intYanYu.ToString();
                    tb2.Cell(2, 3).Range.Text = GenerateWordDocument.AbilityLevel(intYanYu);
                    //第3行 数理能力
                    tb2.Cell(3, 2).Range.Text = intShuLi.ToString();
                    tb2.Cell(3, 3).Range.Text = GenerateWordDocument.AbilityLevel(intShuLi);
                    //第4行 空间判断能力
                    tb2.Cell(4, 2).Range.Text = intKongJianPanDuan.ToString();
                    tb2.Cell(4, 3).Range.Text = GenerateWordDocument.AbilityLevel(intKongJianPanDuan);
                    //第5行 察觉细节能力
                    tb2.Cell(5, 2).Range.Text = intChaJueXiJie.ToString();
                    tb2.Cell(5, 3).Range.Text = GenerateWordDocument.AbilityLevel(intChaJueXiJie);
                    //第6行 书写能力
                    tb2.Cell(6, 2).Range.Text = intShuXie.ToString();
                    tb2.Cell(6, 3).Range.Text = GenerateWordDocument.AbilityLevel(intShuXie);
                    //第7行 运动协调能力
                    tb2.Cell(7, 2).Range.Text = intYunDongXieTiao.ToString();
                    tb2.Cell(7, 3).Range.Text = GenerateWordDocument.AbilityLevel(intYunDongXieTiao);
                    //第8行 动手能力
                    tb2.Cell(8, 2).Range.Text = intDongShou.ToString();
                    tb2.Cell(8, 3).Range.Text = GenerateWordDocument.AbilityLevel(intDongShou);
                    //第9行 社会交往能力
                    tb2.Cell(9, 2).Range.Text = intSheHuiJiaoWang.ToString();
                    tb2.Cell(9, 3).Range.Text = GenerateWordDocument.AbilityLevel(intSheHuiJiaoWang);
                    //第10行 组织管理能力
                    tb2.Cell(10, 2).Range.Text = intZuZhiGuanLi.ToString();
                    tb2.Cell(10, 3).Range.Text = GenerateWordDocument.AbilityLevel(intZuZhiGuanLi);
                }
                #endregion


                //
                #region 模板中 占位符的替换

                Microsoft.Office.Interop.Word.Document oDoc = (Microsoft.Office.Interop.Word.Document)doc;
                JieGuoJieXi();

                //学生姓名
                GenerateWordDocument.ReplaceZF(oDoc, "@studentname", infoStudent.StudentName, Type.Missing);

                //你可能喜欢的专业
                for (int i = 0; i < arrTuiJianZhuanYe.Length; i++)
                {
                    GenerateWordDocument.ReplaceZF(oDoc, "@xihuanzhuanye" + i, arrTuiJianZhuanYe[i], Type.Missing);
                }
                if (arrTuiJianZhuanYe.Length < 9)
                {
                    for (int i = arrTuiJianZhuanYe.Length; i < 9; i++)
                    {
                        GenerateWordDocument.ReplaceZF(oDoc, "@xihuanzhuanye" + i, "", Type.Missing);
                    }
                }

                //不建议选择的专业范围
                for (int i = 0; i < arrBuTuiJianZhuanYe.Length; i++)
                {
                    GenerateWordDocument.ReplaceZF(oDoc, "@buxihuanzhuanye" + i, arrBuTuiJianZhuanYe[i], Type.Missing);
                }
                if (arrBuTuiJianZhuanYe.Length < 9)
                {
                    for (int i = arrBuTuiJianZhuanYe.Length; i < 9; i++)
                    {
                        GenerateWordDocument.ReplaceZF(oDoc, "@buxihuanzhuanye" + i, "", Type.Missing);
                    }
                }

                #endregion

                //
                #region 保存到服务器

                //保存doc文档
                oDoc.SaveAs(ref fileName, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                            ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                            ref nothing, ref nothing, ref nothing);
                oDoc.Close(ref nothing, ref nothing, ref nothing);
                app.Quit(ref nothing, ref nothing, ref nothing);

                //输出word 到客户端
                //   GenerateWordDocument.ExtWord(fileName.ToString(), "ts.doc");

                #endregion
            }
            catch (Exception ex)
            {
                //  resultMsg = "导出错误:" + ex.Message;
                app.Quit(ref nothing, ref nothing, ref nothing);
            }
        }
Пример #12
0
        private void printJournal()
        {
            this.Cursor = Cursors.WaitCursor;
            //Объект приложения word
            Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    document    = null;
            //Путь к файлу
            object pathFile = "E:\\zhurnal.docx";
            object missing  = Type.Missing;
            Object falseObj = false;

            try
            {
                //Загружаем документ
                document = application.Documents.Add(ref pathFile, ref missing, ref missing, ref missing);


                //Очищаем параметры поиска
                // ???????
                application.Selection.Find.ClearFormatting();
                application.Selection.Find.Replacement.ClearFormatting();

                //Замена значений
                RPS("@куратор", Journal.Curator.ToString(), application, missing);
                RPS("@должность", Journal.Curator.positionCurator, application, missing);
                RPS("@группа", Journal.Group.numberGroup, application, missing);
                RPS("@курс", Journal.courceGroup.ToString(), application, missing);
                RPS("@шифр", Journal.Group.cipher.ToString(), application, missing);
                RPS("@учебный год", Journal.yearJournal.Year.ToString() + "/" + Journal.yearJournal.AddYears(1).Year, application, missing);
                RPS("@специальность", Journal.Group.specialtyGroup, application, missing);
                Microsoft.Office.Interop.Word.Table tableStatus    = application.ActiveDocument.Tables[5];
                Microsoft.Office.Interop.Word.Table tableStipendia = application.ActiveDocument.Tables[7];

                int jTableSt   = 1;
                int jTableStip = 2;
                foreach (JournalStudent journalStudent in DBobjects.Entities.JournalStudent.Where(p => p.idJournal == Journal.idJournal).ToList().OrderBy(p => p.Student.surnameStudent))
                {
                    if (journalStudent.StatusStudent.nameSatusSt != "Нет")
                    {
                        if (jTableSt > 1)
                        {
                            tableStatus.Rows.Add(ref missing);
                        }
                        tableStatus.Rows[jTableSt].Cells[1].Range.Text = jTableSt.ToString() + ".";
                        tableStatus.Rows[jTableSt].Cells[2].Range.Text = journalStudent.StatusStudent.nameSatusSt;
                        tableStatus.Rows[jTableSt].Cells[3].Range.Text = journalStudent.Student.ToString();
                        jTableSt++;
                    }
                    if (jTableStip > 2)
                    {
                        tableStipendia.Rows.Add(ref missing);
                    }
                    tableStipendia.Rows[jTableStip].Cells[2].Range.Text = journalStudent.Student.surnameStudent + " " + journalStudent.Student.nameStudent + " " + journalStudent.Student.patronymicStudent;
                    if (journalStudent.stipendSemOne == true)
                    {
                        tableStipendia.Rows[jTableStip].Cells[3].Range.Text = "+";
                    }
                    if (journalStudent.stipendSemTwo == true)
                    {
                        tableStipendia.Rows[jTableStip].Cells[4].Range.Text = "+";
                    }
                    jTableStip++;
                }
                Microsoft.Office.Interop.Word.Table tableInfSt = application.ActiveDocument.Tables[6];
                int jTableInfStud = 2;
                Microsoft.Office.Interop.Word.Table tableVladimir = application.ActiveDocument.Tables[8];
                int jTableVladimir = 2;
                Microsoft.Office.Interop.Word.Table tableInogor = application.ActiveDocument.Tables[9];
                int jTableInogor = 2;
                Microsoft.Office.Interop.Word.Table tablefamilyChild = application.ActiveDocument.Tables[10];
                int jTablefamilyChild = 2;
                Microsoft.Office.Interop.Word.Table tableFamily = application.ActiveDocument.Tables[11];
                int jTableFamily = 2;
                Microsoft.Office.Interop.Word.Table tableFamChild = application.ActiveDocument.Tables[12];
                int jTableFamChild = 2;
                Microsoft.Office.Interop.Word.Table tableLargeRelatives = application.ActiveDocument.Tables[13];
                int jLargeRelatives = 2;
                Microsoft.Office.Interop.Word.Table tableIncomplete = application.ActiveDocument.Tables[14];
                int jIncomplete = 2;
                Microsoft.Office.Interop.Word.Table tableInvaildParents = application.ActiveDocument.Tables[15];
                int jInvaildParents = 2;
                Microsoft.Office.Interop.Word.Table tableQuadian = application.ActiveDocument.Tables[16];
                int jQuadian = 2;
                Microsoft.Office.Interop.Word.Table tableInvaildStudent = application.ActiveDocument.Tables[17];
                int            jInvaildStudent = 2;
                List <Student> students        = DBobjects.Entities.Student.Where(p => p.idGroup == Journal.idGroup).ToList();

                students = students.OrderBy(p => p.surnameStudent).ToList();
                foreach (Student student in students)
                {
                    if (jTableInfStud > 2)
                    {
                        tableInfSt.Rows.Add(ref missing);
                    }
                    tableInfSt.Rows[jTableInfStud].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                    if (student.formOfTrainStudent == true)
                    {
                        tableInfSt.Rows[jTableInfStud].Cells[3].Range.Text = "К";
                    }
                    else
                    {
                        tableInfSt.Rows[jTableInfStud].Cells[3].Range.Text = "Б";
                    }
                    tableInfSt.Rows[jTableInfStud].Cells[4].Range.Text = student.dateOfBirthStudent.ToShortDateString();
                    tableInfSt.Rows[jTableInfStud].Cells[5].Range.Text = student.telephoneStudent;


                    if (student.Residence.town.Contains("Владимир") == true)
                    {
                        if (jTableVladimir > 2)
                        {
                            tableVladimir.Rows.Add(ref missing);
                        }
                        tableVladimir.Rows[jTableVladimir].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                        string adress = student.Residence.country + ", " + student.Residence.region + ", " + student.Residence.district + ", " + student.Residence.town + ", " + student.Residence.street + ", " + student.Residence.korpus + ", " + student.Residence.house + ", " + student.Residence.flat + " ";
                        adress = adress.Replace(", ,", ",");
                        adress = adress.Replace(", ,", ",");
                        adress = adress.TrimEnd(',', ' ');
                        tableVladimir.Rows[jTableVladimir].Cells[3].Range.Text = adress;
                        jTableVladimir++;
                    }
                    else
                    {
                        if (jTableInogor > 2)
                        {
                            tableInogor.Rows.Add(ref missing);
                        }
                        tableInogor.Rows[jTableInogor].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                        string adressPerman = student.Residence.country + ", " + student.Residence.region + ", " + student.Residence.district + ", " + student.Residence.town + ", " + student.Residence.street + ", " + student.Residence.korpus + ", " + student.Residence.house + ", " + student.Residence.flat + " ";
                        adressPerman = adressPerman.Replace(", ,", ",");
                        adressPerman = adressPerman.Replace(", ,", ",");
                        adressPerman = adressPerman.TrimEnd(',', ' ');
                        tableInogor.Rows[jTableInogor].Cells[3].Range.Text = adressPerman;

                        if (student.Residence1.idHostel == 0 || student.Residence1.idHostel == null)
                        {
                            string adressTemp = student.Residence1.country + ", " + student.Residence1.region + ", " + student.Residence1.district + ", " + student.Residence1.town + ", " + student.Residence1.street + ", " + student.Residence1.korpus + ", " + student.Residence1.house + ", " + student.Residence1.flat + " ";
                            adressTemp = adressTemp.Replace(", ,", ",");
                            adressTemp = adressTemp.Replace(", ,", ",");
                            adressTemp = adressPerman.TrimEnd(',', ' ');
                            tableInogor.Rows[jTableInogor].Cells[4].Range.Text = adressTemp;
                            jTableInogor++;
                        }
                        else
                        {
                            tableInogor.Rows[jTableInogor].Cells[4].Range.Text = student.Residence1.Hostel.adressHostel + ". Комната " + student.Residence1.room;

                            jTableInogor++;
                        }
                    }
                    if (student.Family.Count() != 0)
                    {
                        Family family = DBobjects.Entities.Family.FirstOrDefault(p => p.idStudent == student.idStudent);
                        if (String.IsNullOrEmpty(family.nameChild) == false)
                        {
                            if (jTablefamilyChild > 2)
                            {
                                tablefamilyChild.Rows.Add(ref missing);
                            }
                            tablefamilyChild.Rows[jTablefamilyChild].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                            tablefamilyChild.Rows[jTablefamilyChild].Cells[3].Range.Text = family.nameChild + "\n" + family.dateOfBirthChild.Value.ToShortDateString();
                            tablefamilyChild.Rows[jTablefamilyChild].Cells[4].Range.Text = family.fullNameSpous + "\n" + family.professionSpous;
                            jTablefamilyChild++;
                        }
                        if (String.IsNullOrEmpty(family.fullNameSpous) == false)
                        {
                            if (jTableFamily > 2)
                            {
                                tableFamily.Rows.Add(ref missing);
                            }
                            if (student.gender == true)
                            {
                                tableFamily.Rows[jTableFamily].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                                tableFamily.Rows[jTableFamily].Cells[3].Range.Text = family.fullNameSpous;
                            }
                            else
                            {
                                tableFamily.Rows[jTableFamily].Cells[3].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                                tableFamily.Rows[jTableFamily].Cells[2].Range.Text = family.fullNameSpous;
                            }
                            if (family.nameChild != null)
                            {
                                tableFamily.Rows[jTableFamily].Cells[4].Range.Text = family.nameChild.ToString() + "\n" + family.dateOfBirthChild.Value.ToShortDateString().ToString();
                            }
                            jTableFamily++;
                        }
                        if (String.IsNullOrEmpty(family.nameChild) == false && student.gender == true && String.IsNullOrEmpty(family.fullNameSpous) == true)
                        {
                            if (jTableFamChild > 2)
                            {
                                tableFamChild.Rows.Add(ref missing);
                            }
                            tableFamChild.Rows[jTableFamChild].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                            tableFamChild.Rows[jTableFamChild].Cells[3].Range.Text = family.nameChild + "\n" + family.dateOfBirthChild.Value.ToShortDateString();
                            jTableFamChild++;
                        }
                    }
                    List <Kin> kins = DBobjects.Entities.Kin.Where(p => p.idStudent == student.idStudent).ToList();

                    if (kins.Where(p => p.kinStatus == "Брат" || p.kinStatus == "Сестра").Count() >= 2)
                    {
                        if (jLargeRelatives > 2)
                        {
                            tableLargeRelatives.Rows.Add(ref missing);
                        }
                        tableLargeRelatives.Rows[jLargeRelatives].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                        tableLargeRelatives.Rows[jLargeRelatives].Cells[3].Range.Text = (kins.Where(p => p.kinStatus == "Брат" || p.kinStatus == "Сестра").Count() + 1).ToString();
                        jLargeRelatives++;
                    }
                    if (kins.Where(p => p.kinStatus == "Мать" || p.kinStatus == "Отец" && p.kinStatus != "Опекун").Count() < 2 && kins.Count() != 0)
                    {
                        if (jIncomplete > 2)
                        {
                            tableIncomplete.Rows.Add(ref missing);
                        }
                        tableIncomplete.Rows[jIncomplete].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                        foreach (Kin kin in kins)
                        {
                            if (kin.kinStatus == "Мать")
                            {
                                tableIncomplete.Rows[jIncomplete].Cells[3].Range.Text = kin.kinStatus + " " + kin.fullNameKin + "\nОтец -";
                            }
                            if (kin.kinStatus == "Отец")
                            {
                                tableIncomplete.Rows[jIncomplete].Cells[3].Range.Text = kin.kinStatus + " " + kin.fullNameKin + "\nМать -";
                            }
                        }
                        jIncomplete++;
                    }
                    foreach (Kin kin in kins)
                    {
                        if (kin.disabilityKin == true && kin.kinStatus != "Опекун" && kin.kinStatus != "Брат" && kin.kinStatus != "Сестра")
                        {
                            if (jInvaildParents > 2)
                            {
                                tableInvaildParents.Rows.Add(ref missing);
                            }
                            tableInvaildParents.Rows[jInvaildParents].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                            tableInvaildParents.Rows[jInvaildParents].Cells[3].Range.Text = kin.fullNameKin;
                            jInvaildParents++;
                        }

                        if (kin.kinStatus == "Опекун")
                        {
                            if (jQuadian > 2)
                            {
                                tableQuadian.Rows.Add(ref missing);
                            }
                            tableQuadian.Rows[jQuadian].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                            tableQuadian.Rows[jQuadian].Cells[3].Range.Text = kin.fullNameKin + "\n" + kin.telephoneKin;
                            jQuadian++;
                        }
                    }
                    if (student.disabilityStudent == true)
                    {
                        if (jInvaildStudent > 2)
                        {
                            tableInvaildStudent.Rows.Add(ref missing);
                        }
                        tableInvaildStudent.Rows[jInvaildStudent].Cells[2].Range.Text = student.surnameStudent + " " + student.nameStudent + " " + student.patronymicStudent;
                        String rez = "";
                        foreach (Kin kin in kins)
                        {
                            if (kin.kinStatus == "Мать" || kin.kinStatus == "Отец" || kin.kinStatus == "Опекун")
                            {
                                rez += kin.kinStatus + " " + kin.fullNameKin + "\n";
                            }
                        }
                        rez = rez.TrimEnd('\n', ' ');
                        tableInvaildStudent.Rows[jInvaildStudent].Cells[3].Range.Text = rez;
                    }
                    jTableInfStud++;
                }
                Microsoft.Office.Interop.Word.Table tableDynamics = application.ActiveDocument.Tables[18];
                int jDynamics = 3;
                foreach (GroupDynamics groupDynamics in DBobjects.Entities.GroupDynamics.Where(p => p.idJournal == Journal.idJournal).ToList())
                {
                    if (jDynamics > 3)
                    {
                        tableDynamics.Rows.Add(ref missing);
                    }
                    tableDynamics.Cell(jDynamics, 2).Range.Text = groupDynamics.CoreIndicator.ToString();
                    tableDynamics.Cell(jDynamics, 3).Range.Text = Math.Round(groupDynamics.semesterOneDyn, 2).ToString();
                    tableDynamics.Cell(jDynamics, 4).Range.Text = Math.Round(Convert.ToDouble(groupDynamics.semesterTwoDyn), 2).ToString();
                    tableDynamics.Cell(jDynamics, 5).Range.Text = groupDynamics.note;
                    jDynamics++;
                }

                Microsoft.Office.Interop.Word.Table tableGrafik = application.ActiveDocument.Tables[19];
                int jGrafic = 4;
                foreach (StudyingProcess studyingProcess in DBobjects.Entities.StudyingProcess.Where(p => p.idJournal == Journal.idJournal).ToList())
                {
                    if (jGrafic > 4)
                    {
                        tableGrafik.Rows.Add(ref missing);
                    }
                    tableGrafik.Cell(jGrafic, 1).Range.Text = Journal.courceGroup.ToString();
                    tableGrafik.Cell(jGrafic, 2).Range.Text = studyingProcess.semester.ToString();
                    tableGrafik.Cell(jGrafic, 3).Range.Text = studyingProcess.semesterStart.ToShortDateString();
                    tableGrafik.Cell(jGrafic, 4).Range.Text = studyingProcess.semesterEnd.ToShortDateString();
                    tableGrafik.Cell(jGrafic, 5).Range.Text = studyingProcess.sessionStart.ToShortDateString() + "/\n" + studyingProcess.sessionEnd.ToShortDateString();
                    if (studyingProcess.practiceProductStart != null && studyingProcess.practiceTrainStart != null)
                    {
                        tableGrafik.Cell(jGrafic, 6).Range.Text = Convert.ToDateTime(studyingProcess.practiceProductStart).ToShortDateString() + "/\n" + Convert.ToDateTime(studyingProcess.practiceProductEnd).ToShortDateString() + "\n" + Convert.ToDateTime(studyingProcess.practiceTrainStart).ToShortDateString() + "/\n" + Convert.ToDateTime(studyingProcess.practiceTrainEnd).ToShortDateString();
                    }
                    else if (studyingProcess.practiceProductStart != null && studyingProcess.practiceTrainStart == null)
                    {
                        tableGrafik.Cell(jGrafic, 6).Range.Text = Convert.ToDateTime(studyingProcess.practiceProductStart).ToShortDateString() + "/\n" + Convert.ToDateTime(studyingProcess.practiceProductEnd).ToShortDateString();
                    }
                    else if (studyingProcess.practiceProductStart == null && studyingProcess.practiceTrainStart != null)
                    {
                        tableGrafik.Cell(jGrafic, 6).Range.Text = Convert.ToDateTime(studyingProcess.practiceTrainStart).ToShortDateString() + "/\n" + Convert.ToDateTime(studyingProcess.practiceTrainEnd).ToShortDateString();
                    }
                    tableGrafik.Cell(jGrafic, 7).Range.Text = studyingProcess.holidaysStart.ToShortDateString() + "/\n" + studyingProcess.holidaysEnd.ToShortDateString();
                    jGrafic++;
                }
                Microsoft.Office.Interop.Word.Table tableMeeting = application.ActiveDocument.Tables[20];
                int jMeeting = 2;
                foreach (Meeting meeting in DBobjects.Entities.Meeting.Where(p => p.idJournal == Journal.idJournal))
                {
                    if (jMeeting > 2)
                    {
                        tableMeeting.Rows.Add(ref missing);
                    }
                    tableMeeting.Rows[jMeeting].Cells[1].Range.Text = meeting.dateMeeting.ToShortDateString();
                    tableMeeting.Rows[jMeeting].Cells[2].Range.Text = meeting.questionMeeting;
                    String rezMeeting = "";
                    foreach (LackMeeting lackMeeting in DBobjects.Entities.LackMeeting.Where(p => p.idMeeting == meeting.idMeeting))
                    {
                        rezMeeting += lackMeeting.Student.ToString() + ";\n";
                    }
                    rezMeeting = rezMeeting.TrimEnd('\n', ' ');
                    tableMeeting.Rows[jMeeting].Cells[3].Range.Text = rezMeeting;
                    tableMeeting.Rows[jMeeting].Cells[4].Range.Text = meeting.decisionMeeting;
                    jMeeting++;
                }
                Microsoft.Office.Interop.Word.Table tableAttendance = application.ActiveDocument.Tables[21];
                int jAttendance = 2;
                foreach (Attendance attendance in DBobjects.Entities.Attendance.Where(p => p.idJournal == Journal.idJournal))
                {
                    if (jAttendance > 2)
                    {
                        tableAttendance.Rows.Add(ref missing);
                    }
                    tableAttendance.Rows[jAttendance].Cells[1].Range.Text = attendance.dateAttendance.ToShortDateString();
                    tableAttendance.Rows[jAttendance].Cells[2].Range.Text = attendance.Discipline.ToString() + "\n(" + attendance.OccupationStatus.ToString() + ")";
                    tableAttendance.Rows[jAttendance].Cells[3].Range.Text = attendance.fullNameTeach;
                    String rezAttendance = "";
                    foreach (LackAttendance lackAttendance in DBobjects.Entities.LackAttendance.Where(p => p.idAttendance == attendance.idAttendance))
                    {
                        rezAttendance += lackAttendance.Student.ToString() + ";\n";
                    }
                    rezAttendance = rezAttendance.TrimEnd('\n', ' ');
                    tableAttendance.Rows[jAttendance].Cells[4].Range.Text = rezAttendance;
                    jAttendance++;
                }

                Microsoft.Office.Interop.Word.Table tableTalkStudent = application.ActiveDocument.Tables[22];
                int jTalkStudent = 2;
                foreach (PrivateTalk privateTalk in DBobjects.Entities.PrivateTalk.Where(p => p.idJournal == Journal.idJournal))
                {
                    if (jTalkStudent > 2)
                    {
                        tableTalkStudent.Rows.Add(ref missing);
                    }
                    tableTalkStudent.Rows[jTalkStudent].Cells[1].Range.Text = privateTalk.datePrTalk.ToShortDateString();
                    tableTalkStudent.Rows[jTalkStudent].Cells[2].Range.Text = privateTalk.topicPrTalk;
                    String rezPrivTalk = "";
                    foreach (PrivTalkStudent privTalkStudent in DBobjects.Entities.PrivTalkStudent.Where(p => p.idPrTalk == privateTalk.idPrTalk))
                    {
                        rezPrivTalk += privTalkStudent.Student.ToString() + ";\n";
                    }
                    rezPrivTalk = rezPrivTalk.TrimEnd('\n', ' ');
                    tableTalkStudent.Rows[jTalkStudent].Cells[3].Range.Text = rezPrivTalk;
                    jTalkStudent++;
                }

                Microsoft.Office.Interop.Word.Table tableDisciplineComm = application.ActiveDocument.Tables[23];
                int jDisciplineComm = 2;
                foreach (Offense offense in DBobjects.Entities.Offense.Where(p => p.idJournal == Journal.idJournal))
                {
                    if (jDisciplineComm > 2)
                    {
                        tableDisciplineComm.Rows.Add(ref missing);
                    }
                    tableDisciplineComm.Rows[jDisciplineComm].Cells[1].Range.Text = offense.dateOffense.ToShortDateString();
                    tableDisciplineComm.Rows[jDisciplineComm].Cells[2].Range.Text = offense.numberProt;
                    tableDisciplineComm.Rows[jDisciplineComm].Cells[3].Range.Text = offense.causeOffense;
                    tableDisciplineComm.Rows[jDisciplineComm].Cells[4].Range.Text = offense.decisionOffense;
                    jDisciplineComm++;
                }
                Microsoft.Office.Interop.Word.Table tableMessage = application.ActiveDocument.Tables[24];
                int jMessage = 1;
                Microsoft.Office.Interop.Word.Table tableMeet = application.ActiveDocument.Tables[25];
                int jMeet = 1;
                Microsoft.Office.Interop.Word.Table tableDeduction = application.ActiveDocument.Tables[26];
                int jDeduction = 1;
                foreach (TalkParents talkParents in DBobjects.Entities.TalkParents.Where(p => p.idJournal == Journal.idJournal))
                {
                    String kins = "";
                    foreach (StructParentsTalc structParentsTalc in DBobjects.Entities.StructParentsTalc.Where(p => p.idTalkParents == talkParents.idTalkPar).ToList())
                    {
                        kins += structParentsTalc.Kin.fullNameKin + ",";
                    }
                    kins = kins.TrimEnd(',', ' ');
                    if (talkParents.TopicTalkParents.ToString() == "Письмо с уведомлением из деканата")
                    {
                        if (jMessage > 1)
                        {
                            tableMessage.Rows.Add(ref missing);
                        }
                        tableMessage.Rows[jMessage].Cells[1].Range.Text = talkParents.dateTalkPar.ToShortDateString() + " " + talkParents.topicTalc + ". Письмо отправлено: " + kins;
                        jMessage++;
                    }
                    else if (talkParents.TopicTalkParents.ToString() == "Личная встреча")
                    {
                        if (jMeet > 1)
                        {
                            tableMeet.Rows.Add(ref missing);
                        }
                        tableMeet.Rows[jMeet].Cells[1].Range.Text = talkParents.dateTalkPar.ToShortDateString() + " " + talkParents.topicTalc + ". Личная встреча состоялась с: " + kins;
                        jMeet++;
                    }
                    else if (talkParents.TopicTalkParents.ToString() == "Совместно с деканатом факультета и ректоратом решался вопрос об отчислении")
                    {
                        if (jDeduction > 1)
                        {
                            tableDeduction.Rows.Add(ref missing);
                        }
                        tableDeduction.Rows[jDeduction].Cells[1].Range.Text = talkParents.dateTalkPar.ToShortDateString() + " " + talkParents.topicTalc + ". Присутствующие родители: " + kins;
                        jDeduction++;
                    }
                }
                Microsoft.Office.Interop.Word.Table tableVisitHostel = application.ActiveDocument.Tables[27];
                int jVisitHostelHostel = 2;
                foreach (VisitHostel visitHostel in DBobjects.Entities.VisitHostel.Where(p => p.idJournal == Journal.idJournal))
                {
                    if (jVisitHostelHostel > 2)
                    {
                        tableVisitHostel.Rows.Add(ref missing);
                    }
                    tableVisitHostel.Rows[jVisitHostelHostel].Cells[1].Range.Text = visitHostel.dateVisitHostel.ToShortDateString();
                    tableVisitHostel.Rows[jVisitHostelHostel].Cells[2].Range.Text = visitHostel.causeVisitHostel;
                    String hostel = " ";
                    String rooms  = "";
                    foreach (ProvenRooms provenRooms in DBobjects.Entities.ProvenRooms.Where(p => p.idVisitHostel == visitHostel.idVisitHostel))
                    {
                        if (hostel.Contains(" " + provenRooms.Residence.Hostel.ToString() + ", ") == false)
                        {
                            hostel += provenRooms.Residence.Hostel.ToString() + ", ";
                        }
                        rooms += provenRooms.Residence.room + ", ";
                    }
                    hostel = hostel.TrimEnd(',', ' ');
                    rooms  = rooms.TrimEnd(',', ' ');
                    tableVisitHostel.Rows[jVisitHostelHostel].Cells[3].Range.Text = hostel;
                    tableVisitHostel.Rows[jVisitHostelHostel].Cells[4].Range.Text = rooms;
                    jVisitHostelHostel++;
                }
                Microsoft.Office.Interop.Word.Table tableAchivmentNauch = application.ActiveDocument.Tables[28];
                int jNauch = 1;
                Microsoft.Office.Interop.Word.Table tableAchivmentArtists = application.ActiveDocument.Tables[29];
                int jArtists = 1;
                Microsoft.Office.Interop.Word.Table tableAchivmentSports = application.ActiveDocument.Tables[30];
                int jSports = 1;
                Microsoft.Office.Interop.Word.Table tableAchivmentOther = application.ActiveDocument.Tables[31];
                int jOther = 1;
                foreach (Event events in DBobjects.Entities.Event.Where(p => p.idJournal == Journal.idJournal))
                {
                    foreach (AchivementStudent achivementStudent in DBobjects.Entities.AchivementStudent.Where(p => p.idEvent == events.idEvent).ToList())
                    {
                        if (events.TypeOfEvent.ToString() == "Научно-исследовательская работа")
                        {
                            if (jNauch > 1)
                            {
                                tableAchivmentNauch.Rows.Add(ref missing);
                            }
                            tableAchivmentNauch.Rows[jNauch].Cells[1].Range.Text = events.dateEvent.ToShortDateString() + " " + events.nameEvent + " Участник: " + achivementStudent.Student.ToString() + ". Руководитель: " + achivementStudent.fullNameSupervis + ", Тема работы: " + achivementStudent.topicWork + ". (" + achivementStudent.topicAchivment + ")";
                            jNauch++;
                        }
                        else if (events.TypeOfEvent.ToString() == "Художественная самодеятельность")
                        {
                            if (jArtists > 1)
                            {
                                tableAchivmentArtists.Rows.Add(ref missing);
                            }
                            tableAchivmentArtists.Rows[jArtists].Cells[1].Range.Text = events.dateEvent.ToShortDateString() + " " + events.nameEvent + ". Участники: " + achivementStudent.Student.ToString() + ". (" + achivementStudent.topicAchivment + ")";
                            jArtists++;
                        }
                        else if (events.TypeOfEvent.ToString() == "Спортивное мероприятие")
                        {
                            if (jSports > 1)
                            {
                                tableAchivmentSports.Rows.Add(ref missing);
                            }
                            tableAchivmentSports.Rows[jSports].Cells[1].Range.Text = events.dateEvent.ToShortDateString() + " " + events.nameEvent + ". Участник: " + achivementStudent.Student.ToString() + ". (" + achivementStudent.topicAchivment + ")";
                            jSports++;
                        }
                        else
                        {
                            if (jOther > 1)
                            {
                                tableAchivmentOther.Rows.Add(ref missing);
                            }
                            tableAchivmentOther.Rows[jOther].Cells[1].Range.Text = "Тип мероприятия: " + events.TypeOfEvent.ToString() + " " + events.dateEvent.ToShortDateString() + " " + events.nameEvent + ". Участник: " + achivementStudent.Student.ToString() + ". (" + achivementStudent.topicAchivment + ")";
                            jOther++;
                        }
                    }
                }
                saveFileDialogJournal.FileName = "Журнал группы " + Journal.Group.numberGroup + " за " + Journal.courceGroup.ToString() + " курс.docx";
                if (saveFileDialogJournal.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }
                // получаем выбранный файл
                object SaveAsFile = saveFileDialogJournal.FileName;
                document.SaveAs2(SaveAsFile, missing, missing, missing);
                document.Close(ref falseObj, ref missing, ref missing);
                application.Quit(ref missing, ref missing, ref missing);
                document = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
                application = null;
                //Открываем документ для просмотра.
                System.Diagnostics.Process.Start(SaveAsFile.ToString());
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                MessageBox.Show(ex.Message);
                document.Close(ref falseObj, ref missing, ref missing);
                application.Quit(ref missing, ref missing, ref missing);
                document    = null;
                application = null;
                this.Cursor = Cursors.Default;
                application.Quit();
            }
            this.Cursor = Cursors.Default;
        }
Пример #13
0
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application app = null;
            Microsoft.Office.Interop.Word.Document    doc = null;
            //将要导出的新word文件名
            string physicNewFile = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc";

            try
            {
                app = new Microsoft.Office.Interop.Word.Application();                   //创建word应用程序
                object fileName = System.Windows.Forms.Application.StartupPath + Change; //Year1;//模板文件
                app.Visible = true;
                //打开模板文件
                object oMissing = System.Reflection.Missing.Value;
                doc = app.Documents.Open(ref fileName,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);



                Word.Range range = doc.Paragraphs.Last.Range;
                //object tmp = "BT_CREATE";
                //Word.Range range = app.ActiveDocument.Bookmarks.get_Item(ref tmp).Range;

                //Microsoft.Office.Interop.Word.Range range = app.Selection.Range;
                Microsoft.Office.Interop.Word.Table table = app.Selection.Tables.Add(range, 2, 4, ref oMissing, ref oMissing);
                //设置表格的字体大小粗细
                table.Range.Font.Size = 10;
                table.Range.Font.Bold = 0;

                //设置表格标题
                int rowIndex = 1;
                table.Cell(rowIndex, 1).Range.Text = "班级";
                table.Cell(rowIndex, 2).Range.Text = "姓名";
                table.Cell(rowIndex, 3).Range.Text = "成绩";
                table.Cell(rowIndex, 4).Range.Text = "班主任";

                //循环数据创建数据行

                table.Cell(2, 1).Range.Text = "1";    //班级
                table.Cell(2, 4).Range.Text = "4";    //人数
                table.Cell(2, 2).Range.Text = "2";    //班主任
                table.Cell(2, 3).Range.Text = "3";



                //为表格划线
                range.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle        = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle       = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle      = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle     = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle   = WdLineStyle.wdLineStyleSingle;

                object count = 14;
                //object WdLine = Word.WdUnits.wdLine;//换一行;
                //app.Selection.MoveDown(ref WdLine, ref count, ref oMissing);//移动焦点
                //
                object unit;
                unit = Word.WdUnits.wdStory;
                app.Selection.EndKey(ref unit, ref oMissing);
                app.Selection.TypeParagraph();    //插入段落

                app.Selection.Text = "aaaa";


                Word.Range range1 = doc.Paragraphs.Last.Range;
                //object tmp = "BT_CREATE";
                //Word.Range range = app.ActiveDocument.Bookmarks.get_Item(ref tmp).Range;

                //Microsoft.Office.Interop.Word.Range range = app.Selection.Range;
                Microsoft.Office.Interop.Word.Table table1 = app.Selection.Tables.Add(range1, 5, 5, ref oMissing, ref oMissing);
                //设置表格的字体大小粗细
                table1.Range.Font.Size = 10;
                table1.Range.Font.Bold = 0;


                //为表格划线
                range1.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle        = WdLineStyle.wdLineStyleSingle;
                range1.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle       = WdLineStyle.wdLineStyleSingle;
                range1.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle      = WdLineStyle.wdLineStyleSingle;
                range1.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle     = WdLineStyle.wdLineStyleSingle;
                range1.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
                range1.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle   = WdLineStyle.wdLineStyleSingle;


                //设置表格标题
                int rowIndex1 = 1;
                table1.Cell(rowIndex1, 1).Range.Text = "班级";
                table1.Cell(rowIndex1, 2).Range.Text = "姓名";
                table1.Cell(rowIndex1, 3).Range.Text = "成绩";
                table1.Cell(rowIndex1, 4).Range.Text = "班主任";
                table1.Cell(rowIndex1, 5).Range.Text = "112233";

                //循环数据创建数据行

                table1.Cell(2, 1).Range.Text = "一";    //班级
                table1.Cell(2, 4).Range.Text = "四";    //人数
                table1.Cell(2, 2).Range.Text = "二";    //班主任
                table1.Cell(2, 3).Range.Text = "三";
                table1.Cell(2, 5).Range.Text = "三1";



                //对替换好的word模板另存为一个新的word文档
                doc.SaveAs(System.Windows.Forms.Application.StartupPath + "\\ExcelHeaderTemplate\\" + physicNewFile,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                //这边为了捕获Response.End引起的异常
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭word文档
                }
                if (app != null)
                {
                    app.Quit();//退出word应用程序
                }
            }
        }
        private void Btn_Kontrol_Et_Click(object sender, EventArgs e)
        {
            OpenFileDialog Dosya = new OpenFileDialog();

            Dosya.Filter           = "Word Dosyası |*.docx";
            Dosya.RestoreDirectory = true;
            Dosya.CheckFileExists  = false;
            Dosya.Title            = "Word Dosyanızı Seçiniz...";

            if (Dosya.ShowDialog() == DialogResult.OK)
            {
                OpenFileDialog Document  = new OpenFileDialog();
                string         dosyayolu = Dosya.FileName;
                string         dosya_adi = Dosya.SafeFileName;

                {
                    label1.Text = dosya_adi + " Dosyası Kontrol Ediliyor. Lütfen Bekleyiniz...";

                    richTextBox_Dosya.Clear();


                    Microsoft.Office.Interop.Word.Application wordObject = new Microsoft.Office.Interop.Word.Application();

                    object nullobject = System.Reflection.Missing.Value;



                    Microsoft.Office.Interop.Word.Document docs = wordObject.Documents.Open(dosyayolu);

                    docs.ActiveWindow.Selection.WholeStory();
                    docs.ActiveWindow.Selection.Copy();
                    IDataObject data = Clipboard.GetDataObject();


                    string satir = "";
                    int    i     = 1;
                    int    j     = 1;

                    var docum = new Document();
                    docum = docs;


                    foreach (Microsoft.Office.Interop.Word.Paragraph objParagraph in docs.Paragraphs)
                    {
                        Microsoft.Office.Interop.Word.Font s = docs.Paragraphs[j].Range.Font;



                        if (docs.Paragraphs[j].Range.Text == "ÖNSÖZ")
                        {
                            richTextBox_Dosya.Text += "\n ÖNSÖZ MEVCUTTUR " + i;
                        }
                        else if (docs.Paragraphs[j].Range.ToString() == "İÇİNDEKİLER")
                        {
                            richTextBox_Dosya.Text += "\n İÇİNDEKİLER LİSTESİ MEVCUTTUR" + i;
                        }
                        else if (docs.Paragraphs[j].Range.ToString() == "ÖZET")
                        {
                            richTextBox_Dosya.Text += "\n ÖZET METNİ MEVCUTTUR. " + i;
                        }
                        else if (docs.Paragraphs[j].Range.ToString() == "ABSTRACT")
                        {
                            richTextBox_Dosya.Text += "\n İNGİLİZCE ÖZET METNİ MEVCUTTUR. " + i;
                        }
                        else if (docs.Paragraphs[j].Range.ToString() == "ŞEKİLLER LİSTESİ")
                        {
                            richTextBox_Dosya.Text += "\n ŞEKİLLER LİSTESİ MEVCUTTUR. " + i;
                        }
                        else if (docs.Paragraphs[j].Range.ToString() == "TABLOLAR LİSTESİ")
                        {
                            richTextBox_Dosya.Text += "\n TABLOLAR LİSTESİ MEVCUTTUR. " + i;
                        }
                        else if (docs.Paragraphs[j].Range.ToString() == "EKLER LİSTESİ")
                        {
                            richTextBox_Dosya.Text += "\n EKLER LİSTESİ MEVCUTTUR. " + i;
                        }
                        else if (docs.Paragraphs[j].Range.ToString() == "SİMGELER VE KISALTMALAR")
                        {
                            richTextBox_Dosya.Text += "\n SİMGELER VE KISALTMLAR MEVCUTTUR." + i;
                        }

                        if (s.Size == 12F)
                        {
                            if (s.Position.ToString() != "wdVerticalAlignmentLeft")
                            {
                                richTextBox_Dosya.Text += "\n ara başlık sola yaslı değil satır :" + i;
                            }
                            if (s.ColorIndex.ToString() != "wdBlack")
                            {
                                richTextBox_Dosya.Text += "\n yazı rengi yanlış satır:" + i;
                            }
                            if (s.Name.ToString() != "Times New Roman")
                            {
                                richTextBox_Dosya.Text += "\n yazı stili yanlış satır:" + i;
                            }
                        }
                        else
                        if (s.Size == 16F)
                        {
                            if (s.Position.ToString() != "WdVerticalAlignmentCenter")
                            {
                                richTextBox_Dosya.Text += "\n ana başlık iki yana yaslı değil satır:  " + i;
                            }
                            if (s.ColorIndex.ToString() != "wdBlack")
                            {
                                richTextBox_Dosya.Text += "\n yazı rengi yanlış satır:" + i;
                            }
                            if (s.Name.ToString() != "Times New Roman")
                            {
                                richTextBox_Dosya.Text += "\n yazı stili yanlış satır:" + i;
                            }
                        }
                        else
                        if (s.Size == 11F)
                        {
                            if (s.Position.ToString() != "WdVerticalAlignmentCenter")
                            {
                                richTextBox_Dosya.Text += "\n ana başlık iki yana yaslı değil satır:  " + i;
                            }
                            if (s.ColorIndex.ToString() != "wdBlack")
                            {
                                richTextBox_Dosya.Text += "\n yazı rengi yanlış satır:" + i;
                            }
                            if (s.Name.ToString() != "Times New Roman")
                            {
                                richTextBox_Dosya.Text += "\n yazı stili yanlış satır:" + i;
                            }
                        }

                        else
                        {
                            richTextBox_Dosya.Text += "\n yazı boyutu 11 punto değil satır:" + i;

                            if (s.Name.ToString() != "Times New Roman")
                            {
                                richTextBox_Dosya.Text += "\n yazı stili yanlış satır:" + i;
                            }
                            if (s.ColorIndex.ToString() != "wdBlack")
                            {
                                richTextBox_Dosya.Text += "\n yazı rengi yanlış satır:" + i;
                            }
                        }


                        i++;
                        j++;
                    }

                    i = 1;
                    j = 1;

                    if (docum.PageSetup.TopMargin.ToString() != "85,05")
                    {
                        richTextBox_Dosya.Text += "\n üst boşluk yanlış:";
                    }

                    if (docum.PageSetup.LeftMargin.ToString() != "92,15")
                    {
                        richTextBox_Dosya.Text += "\n sol boşluk yanlış:";
                    }

                    if (docum.PageSetup.RightMargin.ToString() != "70,9")
                    {
                        richTextBox_Dosya.Text += "\n sağ boşluk yanlış:";
                    }

                    if (docum.PageSetup.BottomMargin.ToString() != "70,9")
                    {
                        richTextBox_Dosya.Text += "\n alt boşluk yanlış:";
                    }

                    if (docum.Paragraphs.Alignment != WdParagraphAlignment.wdAlignParagraphCenter)
                    {
                        richTextBox_Dosya.Text += "\n iki yana yaslı değil";

                        label1.Text = dosya_adi + " Dosyası Kontrol Edildi. Ayrıntılar Aşağıdaki Kısımdadır.";
                    }

                    MessageBox.Show("Tarama İşlemi Tamamlandı", "BİLGİ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    docs.Close(ref nullobject, ref nullobject, ref nullobject);


git:
                    return;
                }
            }
        }
Пример #15
0
        public void ChangeTextForFaktura(string[] data)
        {
            if (data.Length == 17)
            {
                object templateForFaktura = "Y:\\Legalizace\\Templates\\faktura.docx";

                //now create word file into template and fill data
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

                //load document
                Microsoft.Office.Interop.Word.Document doc = null;

                object missing = Type.Missing;

                doc = app.Documents.Open(templateForFaktura, missing, missing);
                app.Selection.Find.ClearFormatting();
                app.Selection.Find.Replacement.ClearFormatting();

                string[] tmpForData = new string[17];
                tmpForData = data;

                app.Selection.Find.Execute("<GoodsName>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[0], 2);
                app.Selection.Find.Execute("<Type>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[1], 2);
                app.Selection.Find.Execute("<Qant>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[2], 2);
                app.Selection.Find.Execute("<Price>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[3], 2);
                app.Selection.Find.Execute("<Currency>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[4], 2);
                app.Selection.Find.Execute("<DateWystawenia>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[5], 2);
                app.Selection.Find.Execute("<DateSprzedazy>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[6], 2);
                app.Selection.Find.Execute("<NameOfPlCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[7], 2);
                app.Selection.Find.Execute("<AddresPlCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[8], 2);
                app.Selection.Find.Execute("<IcPlCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[9], 2);
                app.Selection.Find.Execute("<NameOfCzCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[10], 2);
                app.Selection.Find.Execute("<AddresOfCZCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[11], 2);
                app.Selection.Find.Execute("<IcOfCZCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[12], 2);
                app.Selection.Find.Execute("<NumberOfFactura>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[13], 2);
                app.Selection.Find.Execute("<gotowka>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[14], 2);
                app.Selection.Find.Execute("<AllCountPrice>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[15], 2);
                app.Selection.Find.Execute("<PriceToWords>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[16], 2);

                object FilePathForFaktura = (object)"Y:\\Legalizace\\Faktury\\" + tmpForData[7] + "_" + tmpForData[10] + "_" + tmpForData[13] + "_" + tmpForData[14] + "_Faktura.docx";
                doc.SaveAs2(FilePathForFaktura, missing, missing, missing);

                MessageBox.Show("Files Are Created!");
                doc.Close(false, missing, missing);
                app.Quit(false, false, false);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
            }
            else
            {
                object templateForFakturaTrans = "Y:\\Legalizace\\Templates\\fakturaTrans.docx";

                //now create word file into template and fill data
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

                //load document
                Microsoft.Office.Interop.Word.Document doc = null;

                object missing = Type.Missing;

                doc = app.Documents.Open(templateForFakturaTrans, missing, missing);
                app.Selection.Find.ClearFormatting();
                app.Selection.Find.Replacement.ClearFormatting();

                string[] tmpForData = new string[22];
                tmpForData = data;

                app.Selection.Find.Execute("<GoodsName>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[0], 2);
                app.Selection.Find.Execute("<Type>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[1], 2);
                app.Selection.Find.Execute("<Qant>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[2], 2);
                app.Selection.Find.Execute("<Price>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[3], 2);
                app.Selection.Find.Execute("<Currency>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[4], 2);
                app.Selection.Find.Execute("<DateWystawenia>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[5], 2);
                app.Selection.Find.Execute("<DateSprzedazy>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[6], 2);
                app.Selection.Find.Execute("<NameOfPlCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[7], 2);
                app.Selection.Find.Execute("<AddresPlCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[8], 2);
                app.Selection.Find.Execute("<IcPlCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[9], 2);
                app.Selection.Find.Execute("<NameOfCzCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[10], 2);
                app.Selection.Find.Execute("<AddresOfCZCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[11], 2);
                app.Selection.Find.Execute("<IcOfCZCompany>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[12], 2);
                app.Selection.Find.Execute("<NumberOfFactura>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[13], 2);
                app.Selection.Find.Execute("<PayTime>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[14], 2);
                app.Selection.Find.Execute("<Konto>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[15], 2);
                app.Selection.Find.Execute("<IBAN>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[16], 2);
                app.Selection.Find.Execute("<KontoNumber>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[17], 2);
                app.Selection.Find.Execute("<SWIFT>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[18], 2);
                app.Selection.Find.Execute("<przelew>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[19], 2);
                app.Selection.Find.Execute("<AllCountPrice>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[20], 2);
                app.Selection.Find.Execute("<PriceToWords>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[21], 2);

                object FilePathForFaktura = (object)"Y:\\Legalizace\\Faktury\\" + tmpForData[7] + "_" + tmpForData[10] + "_" + tmpForData[20] + "_" + tmpForData[19] + "_Faktura.docx";
                doc.SaveAs2(FilePathForFaktura, missing, missing, missing);

                MessageBox.Show("Files Are Created!");
                doc.Close(false, missing, missing);
                app.Quit(false, false, false);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
            }
        }
Пример #16
0
        private void button1_Click(object sender, EventArgs e)
        {
/*            string res = "C:\\Users\\twimy\\OneDrive\\Desktop\\FINKI\\iSolve\\C# Word templates\\Form.xlsx";
 *          Excel.Application xlApp;
 *          Excel.Workbook xlWorkBook;
 *          Excel.Worksheet xlWorkSheet;
 *
 *          xlApp = new Excel.Application();
 *          xlWorkBook = xlApp.Workbooks.Open(res, 0, true, 5, "", "", true);
 *          xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
 */

            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

            //dokumenti excel per numrimin e reshtave...
            //string exceldoc = "C:\\Users\\twimy\\OneDrive\\Desktop\\FINKI\\iSolve\\C# Word templates\\Form.xlsx";
            string exceldoc = textBox1.Text;

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook    sheet = excel.Workbooks.Open(exceldoc);
            Microsoft.Office.Interop.Excel.Worksheet   x     = excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;

            Excel.Range userRange    = x.UsedRange;
            int         countRecords = userRange.Rows.Count;

            //int add = countRecords +1;
            //x.Cells[add, 1] = "Total Rows "+countRecords;

            //progress bar
            this.progressBar1.Maximum = 100;

            //dokumenti template
            Microsoft.Office.Interop.Word.Document doc = null;
            object fileName = textBox2.Text;
            //object fileName = "C:\\Users\\twimy\\OneDrive\\Desktop\\FINKI\\iSolve\\C# Word templates\\Template.docx";
            object missing = Type.Missing;

            for (int i = 0; i < countRecords; i++)
            {
                doc = app.Documents.Open(fileName, missing, missing);
                app.Selection.Find.ClearFormatting();
                app.Selection.Find.Replacement.ClearFormatting();

                string[] tmp = new string[4];
                tmp = readExcel(i);

                app.Selection.Find.Execute("<ID>", missing, missing, missing, missing, missing, missing, missing, missing, tmp[0], 2);
                app.Selection.Find.Execute("<name>", missing, missing, missing, missing, missing, missing, missing, missing, tmp[1], 2);
                app.Selection.Find.Execute("<sex>", missing, missing, missing, missing, missing, missing, missing, missing, tmp[2], 2);
                app.Selection.Find.Execute("<age>", missing, missing, missing, missing, missing, missing, missing, missing, tmp[3], 2);


                object SaveAsFile = (object)textBox3.Text + "\\Report" + tmp[0] + ".doc";
                doc.SaveAs2(SaveAsFile, missing, missing, missing);
                this.progressBar1.Value += (100 / countRecords);
            }
            this.progressBar1.Value = 100;
            MessageBox.Show("Fajllat u krijuan me sukses!");
            doc.Close(false, missing, missing);
            app.Quit(false, false, false);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
            sheet.Close(true, Type.Missing, Type.Missing);
            excel.Quit();
        }
Пример #17
0
        /// <summary>
        /// 导出Word 的方法
        /// </summary>
        private void tslExport_Word()
        {
            #region 方法一
            SaveFileDialog sfile = new SaveFileDialog();
            sfile.AddExtension = true;
            sfile.DefaultExt   = ".doc";
            sfile.Filter       = "(*.doc)|*.doc";
            sfile.FileName     = "理文检测系统车辆质检统计Word报表" + DateTime.Now.ToShortDateString();
            if (sfile.ShowDialog() == DialogResult.OK)
            {
                object path = sfile.FileName;
                Object none = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Application wordApp  = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
                //建立表格
                Microsoft.Office.Interop.Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, dgvCarStatisticsQC.Rows.Count + 1, dgvCarStatisticsQC.Columns.Count, ref none, ref none);
                try
                {
                    for (int i = 0; i < dgvCarStatisticsQC.Columns.Count; i++)//设置标题
                    {
                        table.Cell(0, i + 1).Range.Text = dgvCarStatisticsQC.Columns[i].HeaderText;
                    }
                    //for (int i = 0; i < dgvCarStatisticsQC.Rows.Count; i++)//填充数据
                    //{
                    //    i++;
                    //    for (int j = 0; j < dgvCarStatisticsQC.Columns.Count; j++)
                    //    {
                    //        //if (dgvCarStatisticsQC[i-1, j].Value != null)
                    //        //{
                    //            table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC.Rows[i-1].Cells[j].Value.ToString();
                    //        //}
                    //    }
                    //}

                    for (int i = 1; i <= dgvCarStatisticsQC.Rows.Count; i++)       //填充数据
                    {
                        for (int j = 0; j < dgvCarStatisticsQC.Columns.Count; j++) //dgvCarStatisticsQC.Columns.Count
                        {
                            //table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                            if (dgvCarStatisticsQC[j, i - 1].Value != null)
                            {
                                // table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                                table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                            }
                            else
                            {
                                table.Cell(i + 1, j + 1).Range.Text = "";
                            }
                        }
                    }

                    document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
                    document.Close(ref none, ref none, ref none);
                    MessageBox.Show("导出数据成功!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    wordApp.Quit(ref none, ref none, ref none);
                }
            }
            #endregion

            #region 方法二
            //Word.Document mydoc = new Word.Document();
            //Word.Table mytable = null;
            //Word.Selection mysel;
            //Object myobj;

            ////建立Word对象
            //Word.Application word = new Word.Application();
            //myobj = System.Reflection.Missing.Value;
            //mydoc = word.Documents.Add(ref myobj, ref myobj, ref myobj, ref myobj);
            //word.Visible = true;
            //mydoc.Select();
            //mysel = word.Selection;
            ////将数据生成Word表格文件
            //mytable = mydoc.Tables.Add(mysel.Range, this.dgvCarStatisticsQC.RowCount, this.dgvCarStatisticsQC.ColumnCount, ref myobj, ref myobj);
            ////设置列宽
            //mytable.Columns.SetWidth(30, Word.WdRulerStyle.wdAdjustNone);
            ////输出列标题数据
            //for (int i = 0; i < this.dgvCarStatisticsQC.ColumnCount; i++)
            //{
            //    mytable.Cell(1, i + 1).Range.InsertAfter(this.dgvCarStatisticsQC.Columns[i].HeaderText);
            //}
            ////输出控件中的记录
            //for (int i = 0; i < this.dgvCarStatisticsQC.RowCount - 1; i++)
            //{
            //    for (int j = 0; j < this.dgvCarStatisticsQC.ColumnCount; j++)
            //    {
            //        mytable.Cell(i + 2, j + 1).Range.InsertAfter(this.dgvCarStatisticsQC[j, i].Value.ToString());
            //    }
            //}
            #endregion
        }
Пример #18
0
        /// <summary>
        /// 通过Word模板标签生成word
        /// </summary>
        /// <param name="templateFileName">模板文件路径</param>
        /// <param name="exportFileName">新文件路径</param>
        /// <param name="info">需要导出的信息键值对,key为模板标签名,value为需要导出的信息</param>
        /// <param name="startPageIndex">word页数</param>
        public static bool ExportWord(string templateFileName, string exportFileName, Dictionary <string, WordExportInfo> info)
        {
            //生成documnet对象
            Word._Document doc = new Microsoft.Office.Interop.Word.Document();
            //生成word程序对象
            Word.Application app = new Word.Application();
            //模板文件
            //模板文件拷贝到新文件
            File.Copy(templateFileName, exportFileName);

            object Obj_FileName = exportFileName;
            object Visible      = false;
            object ReadOnly     = false;
            object missing      = System.Reflection.Missing.Value;

            try
            {
                //打开文件
                doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                                         ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing, ref Visible,
                                         ref missing, ref missing, ref missing,
                                         ref missing);
                doc.Activate();

                #region 将文本或图片插入到模板中对应标签
                if (info.Count > 0)
                {
                    object what = Word.WdGoToItem.wdGoToBookmark;
                    object WordMarkName;
                    foreach (var item in info)
                    {
                        WordMarkName = item.Key;
                        //光标转到书签的位置
                        doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref WordMarkName);
                        //插入的内容,插入位置是word模板中书签定位的位置
                        if (item.Value.ImagePath == null)
                        {
                            doc.ActiveWindow.Selection.TypeText(item.Value.Text);
                        }
                        else
                        {
                            //注意此处需要对应模板文件的图片处的书签
                            object   oStart           = doc.Bookmarks.get_Item("Image");
                            Object   linkToFile       = false;                                    //图片是否为外部链接
                            Object   saveWithDocument = true;                                     //图片是否随文档一起保存
                            object   range            = doc.Bookmarks.get_Item(ref oStart).Range; //图片插入位置
                            FileInfo filePhotoInfo    = new FileInfo(item.Value.ToString());
                            if (filePhotoInfo.Exists == false)
                            {
                                break;
                            }
                            doc.InlineShapes.AddPicture(item.Value.ImagePath, ref linkToFile, ref saveWithDocument, ref range);
                            doc.Application.ActiveDocument.InlineShapes[1].Width  = 60;  //设置图片宽度
                            doc.Application.ActiveDocument.InlineShapes[1].Height = 70;  //设置图片高度
                        }
                        //设置当前定位书签位置插入内容的格式,建议直接在模板中设置
                        //doc.ActiveWindow.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    }
                }
                #endregion

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
            finally
            {
                //输出完毕后关闭doc对象
                object IsSave = true;
                doc.Close(ref IsSave, ref missing, ref missing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                doc = null;
            }
        }
Пример #19
0
        public void findMathTypeEquations()
        {
            Word.Shapes objects = docOpen.Shapes;
            foreach (Word.Shape shape in objects)
            {
                Console.WriteLine(shape.TextFrame);
            }

            int OMathsCount = myRange.OMaths.Count;

            Console.WriteLine(OMathsCount);
            Console.WriteLine("Bar max:");

            form.progressBar1.Maximum = OMathsCount;


            try
            {
                String     clipboard_memory = Clipboard.GetText();
                Word.Range endRange         = docOpen.Range(myRange.End - 1, myRange.End - 1);



                if (OMathsCount > 0)
                {
                    string final_eq_file_path_clear = this.inputFileDir + @"\EquationsFile.txt";
                    File.WriteAllText(final_eq_file_path_clear, String.Empty);

                    string temp_file_path = this.inputFileDir + @"\EquationTemporaryFile.txt";
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(temp_file_path))

                    {
                        int  offset = 1;
                        bool empty_eq_fl;
                        bool break_for_fl = false;
                        for (int i = 0; i < OMathsCount && offset <= myRange.OMaths.Count; i++)
                        {
                            empty_eq_fl = true;
                            Thread staThread = new Thread(
                                delegate()
                            {
                                Word.OMath currentEquation = myRange.OMaths[offset];
                                while (empty_eq_fl)
                                {
                                    try
                                    {
                                        currentEquation.Range.Select();

                                        currentEquation.Range.TextRetrievalMode.IncludeHiddenText = true;
                                        currentEquation.Range.TextRetrievalMode.IncludeFieldCodes = true;

                                        currentEquation.Range.Application.Selection.Copy();
                                        empty_eq_fl = false;
                                    }
                                    catch (System.Runtime.InteropServices.COMException ex)
                                    {
                                        if (offset <= myRange.OMaths.Count - 1)
                                        {
                                            offset++;
                                            currentEquation = myRange.OMaths[offset];
                                        }
                                        else
                                        {
                                            break_for_fl = true;
                                            break;
                                        }
                                    }
                                }
                                if (!break_for_fl)
                                {
                                    //currentEquation.Range.Application.Selection.Range.HighlightColorIndex = Word.WdColorIndex.wdYellow;
                                    String tekst     = Clipboard.GetText();
                                    String new_tekst = "$";
                                    /////////////////////////////////////////////////////////////////////////////////////

                                    char[] tokens   = tekst.ToCharArray();
                                    string[] parsed = TranslateTokensToTex(tokens);
                                    for (int p = 0; p < parsed.Length; p++)
                                    {
                                        Console.Write(parsed[p] + "^.^");
                                    }
                                    Console.WriteLine("---------------------------------------------------");
                                    for (int p = 0; p < parsed.Length; p++)
                                    {
                                        parsed[p] = ParseToken(ref parsed, p);
                                    }
                                    for (int p = 0; p < parsed.Length; p++)
                                    {
                                        if (parsed[p] != @"")
                                        {
                                            new_tekst += parsed[p];
                                        }
                                    }
                                    new_tekst += "$";
                                    /////////////////////////////////////////////////////////////////////////////////////
                                    file.WriteLine(tekst);

                                    string final_eq_file_path = this.inputFileDir + @"\EquationsFile.txt";
                                    using (System.IO.StreamWriter file2 = File.AppendText(final_eq_file_path))
                                    {
                                        file2.WriteLine(new_tekst);
                                    }

                                    if (clipboard_memory.CompareTo("") != 0)
                                    {
                                        Clipboard.SetText(clipboard_memory);
                                    }
                                    else
                                    {
                                        Clipboard.Clear();
                                    }

                                    //removing text from start to end

                                    int start = currentEquation.Range.Start;
                                    int end   = currentEquation.Range.End;
                                    currentEquation.Range.Application.Selection.Delete();

                                    if (new_tekst != "$$")
                                    {
                                        currentEquation.Range.InsertBefore(new_tekst);
                                    }
                                }
                            });

                            staThread.SetApartmentState(ApartmentState.STA);
                            staThread.Start();
                            staThread.Join();
                            form.progressBar1.PerformStep();
                            if (break_for_fl)
                            {
                                break;
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("No equations found.");
                }

                if (form.checkBox2.Checked == false)
                {
                    docOpen.SaveAs(second_file_path);
                }
                else
                {
                    docOpen.SaveAs();
                }
                docOpen.Close();
                app.Quit();

                string final_message = "Process Completed\n\nFile \"EquationsFile.txt\" containing all converted equations and needed packages.\n";
                if (packages.Count != 0)
                {
                    final_message += "Additional packages required for further use:\n";
                    string final_eq_file_path = this.inputFileDir + @"\EquationsFile.txt";
                    using (System.IO.StreamWriter file2 = File.AppendText(final_eq_file_path))
                    {
                        file2.WriteLine("\n" + @"\usepackage{amsmath}");
                        foreach (string pack in packages)
                        {
                            final_message += pack;
                            final_message += "\n";
                            file2.WriteLine(pack);
                        }
                    }
                }
                MessageBox.Show(final_message);
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #20
0
        private void createEmptyFiles()
        {
            int filesToCreateTemp = frm1.filesToCreate;

            try
            {
                string emptyWorkingDir = frm1.workingDirectory + "Empty Files\\";
                System.IO.Directory.CreateDirectory(emptyWorkingDir);
                int    documentCount     = 0;
                string emptyFileNameDate = frm1.emptyFileName + DateTime.Now.ToString("dd-M-yyyy_HH-mm");
                string emptyFileNameFinal;

                // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Word instance ~~~~~~~~~~~~~~~~~~~~~~~~~
                var winwordEmpty = new Microsoft.Office.Interop.Word.Application();
                winwordEmpty.ShowAnimation = false;
                winwordEmpty.Visible       = false;
                object winWordMissing = System.Reflection.Missing.Value;
                // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

                // ~~~~~~~~~~~~~~~~~~~~~~~~~ Excel instance ~~~~~~~~~~~~~~~~~~~~~~~~~
                Microsoft.Office.Interop.Excel.Application excelEmpty;
                Microsoft.Office.Interop.Excel.Workbook    workBookEmpty;
                Microsoft.Office.Interop.Excel.Worksheet   workSheetEmpty;
                excelEmpty               = new Microsoft.Office.Interop.Excel.Application();
                excelEmpty.Visible       = false;
                excelEmpty.DisplayAlerts = false;
                // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

                while (documentCount < filesToCreateTemp)
                {
                    emptyFileNameFinal = emptyFileNameDate + "_" + documentCount;    // index of file (at filename)

                    // ~~~~ create empty word files
                    if (frm1.usingWordFiles)
                    {
                        try
                        {
                            //Create a new document
                            Microsoft.Office.Interop.Word.Document emptyDocument = winwordEmpty.Documents.Add(ref winWordMissing, ref winWordMissing, ref winWordMissing, ref winWordMissing);
                            emptyDocument.Content.SetRange(0, 0);
                            //Save the document
                            object filename = emptyWorkingDir + emptyFileNameFinal + ".docx";
                            emptyDocument.SaveAs2(ref filename);
                            // Keeping a list of files created
                            frm1.listOfEmptyWordFiles.Add(filename.ToString());
                            emptyDocument.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                            emptyDocument = null;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error creating empty word file");
                            Console.WriteLine(ex.Message);
                        }
                    }

                    // ~~~~ create empty excel files
                    if (frm1.usingExcelFiles)
                    {
                        try
                        {
                            //Create a new WorkBook
                            workBookEmpty  = excelEmpty.Workbooks.Add(Type.Missing);
                            workSheetEmpty = (Microsoft.Office.Interop.Excel.Worksheet)workBookEmpty.ActiveSheet;

                            //Save the document
                            object filename = emptyWorkingDir + emptyFileNameFinal + ".xlsx";
                            workBookEmpty.SaveAs(filename);
                            // Keeping a list of files created
                            frm1.listOfEmptyExcelFiles.Add(filename.ToString());
                            workBookEmpty.Close();
                            workBookEmpty  = null;
                            workSheetEmpty = null;
                            if (workSheetEmpty != null)
                            {
                                Marshal.ReleaseComObject(workSheetEmpty);
                            }
                            if (workBookEmpty != null)
                            {
                                Marshal.ReleaseComObject(workBookEmpty);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error creating empty excel file");
                            Console.WriteLine(ex.Message);
                        }
                        //workBookEmpty = null;
                        //workSheetEmpty = null;
                    }
                    documentCount++;
                }
                // ~~~~~~~~~~~~~~~~~~~~ Terminating Word instance ~~~~~~~~~~~~~~~~~~~
                winwordEmpty.Quit(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                winwordEmpty.Quit();
                if (winwordEmpty != null)
                {
                    Marshal.ReleaseComObject(winwordEmpty);
                }
                winwordEmpty = null;
                // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

                // ~~~~~~~~~~~~~~~~~~~ Terminating Excel instance ~~~~~~~~~~~~~~~~~~~
                excelEmpty.Quit();
                excelEmpty = null;
                if (excelEmpty != null)
                {
                    Marshal.ReleaseComObject(excelEmpty);
                }
                // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error creating empty files");
                Console.WriteLine(ex.Message);
            }
            tskCreateEmptyRunning = false;
            Console.WriteLine();
            Console.WriteLine("runEverything(): createEmptyFiles() -> DONE");
        }
        private void btnNuevo_Click(object sender, EventArgs e)
        {
            Word.Application appWord = new Word.Application();
            appWord.ScreenUpdating = false;
            appWord.DisplayAlerts  = 0;
            appWord.Visible        = false;
            try
            {
                StringBuilder strHTMLContent = new StringBuilder();
                //strHTMLContent.Append("<html>");
                //strHTMLContent.Append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
                //strHTMLContent.Append("<body>");

                //iTextSharp.text.Document oDoc = new iTextSharp.text.Document();
                //PdfWriter.GetInstance(oDoc, new FileStream("HelloWorld.pdf", FileMode.Create));
                //oDoc.Open();
                //oDoc.Add(new Paragraph("Hello World!"));
                //oDoc.Close();

                //Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
                int    count         = 0;
                bool   flg           = false;
                string IdPagadoraOld = string.Empty;
                foreach (DataGridViewRow row in dgvDatos.Rows)
                {
                    if (row.Cells["FlgEnviar"].Value.ToString().Equals("1"))
                    {
                        count++;
                        if (count == 1)
                        {
                            IdPagadoraOld = row.Cells["IdPagadora"].Value.ToString().Trim();
                            //Instanciando un nuevo documento
                            strHTMLContent = new StringBuilder();
                            strHTMLContent.Append("<html>");
                            strHTMLContent.Append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
                            strHTMLContent.Append("<body>");
                            flg = true;
                        }

                        if (IdPagadoraOld != row.Cells["IdPagadora"].Value.ToString().Trim())
                        {
                            strHTMLContent.Append("</body></html>");
                            string     strPath = "d:\\" + IdPagadoraOld + ".doc";
                            FileStream fStream = File.Create(strPath);
                            fStream.Close();
                            fStream = null;
                            //fStream.Dispose();

                            StreamWriter sWriter = new StreamWriter(strPath);
                            sWriter.Write(strHTMLContent);
                            sWriter.Close();
                            wordDocument = appWord.Documents.Open(@"D:\" + IdPagadoraOld + ".doc");
                            wordDocument.ExportAsFixedFormat(@"D:\" + IdPagadoraOld + ".pdf", WdExportFormat.wdExportFormatPDF);
                            wordDocument.Close(SaveChanges = false);
                            //appWord.Documents.Close();
                            //appWord = null;
                            //appWord = new Microsoft.Office.Interop.Word.Application();

                            flg = false;

                            //Instanciando un nuevo documento
                            strHTMLContent = new StringBuilder();
                            strHTMLContent.Append("<html>");
                            strHTMLContent.Append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
                            strHTMLContent.Append("<body>");
                        }

                        int CountRow = 0;
                        while (CountRow < 2)
                        {
                            string dir0 = row.Cells["DireccionSocio"].Value.ToString().Trim();
                            string dir1 = "";
                            string dir2 = "";
                            string dir3 = "";

                            string strFechaVenc = string.IsNullOrEmpty(row.Cells["sdVencimiento"].Value.ToString()) ? "" : Convert.ToDateTime(row.Cells["sdVencimiento"].Value.ToString().Trim()).ToString("d");

                            //if (dir0.Length > 60)
                            //{
                            //    dir1 = dir0.Substring(0, 60);
                            //    dir2 = dir0.Substring(60, dir0.Length-61);
                            //    dir3 = row.Cells["Distrito"].Value.ToString().Trim();
                            //}
                            //else
                            //{
                            dir1 = dir0;
                            dir2 = row.Cells["Distrito"].Value.ToString().Trim();
                            dir3 = "";
                            //}

                            flg = true;
                            strHTMLContent.Append("<table width='100%' style='font-size: 11px;' border='0' cellpadding='0' cellspacing='0'><tr><td width='48%'>");
                            strHTMLContent.Append("<div><img src='J:\\Imagen\\logoEfide2.jpg' style='width:100px;height:30px;'></div>");
                            //strHTMLContent.Append("<br>");
                            strHTMLContent.Append("<br>");
                            strHTMLContent.Append("<div></div>");
                            strHTMLContent.Append("<br>");
                            strHTMLContent.Append("<div>Señores</div>");
                            //strHTMLContent.Append("<br>");
                            strHTMLContent.Append("<div>" + row.Cells["IdPagadora_Dsc"].Value.ToString().Trim() + "</div>");
                            strHTMLContent.Append("<div>" + dir1 + "</div>");
                            strHTMLContent.Append("<div>" + dir2 + "</div>");
                            strHTMLContent.Append("<div>" + dir3 + "</div>");

                            //strHTMLContent.Append("<div>" + row.Cells["DireccionSocio"].Value.ToString().Trim().Substring(51) + "</div>");
                            strHTMLContent.Append("<br>");
                            strHTMLContent.Append("<div><b>Documento:</b></div>");
                            strHTMLContent.Append("<br>");
                            strHTMLContent.Append("<div style='text-align:center'><b>" + row.Cells["cNumDoc"].Value.ToString().Trim() + " (LOTE - " + row.Cells["IdLote"].Value.ToString().Trim() + ")</b></div>");
                            strHTMLContent.Append("<div><b>Doc. Ident. Aceptante:</b> " + row.Cells["RucAceptante"].Value.ToString().Trim() + "</div>");
                            //strHTMLContent.Append("<div><b>Importe:</b> " + row.Cells["IdMoneda_tt_Dsc"].Value.ToString().Trim() + " " + (Convert.ToDecimal(row.Cells["nvNegociable"].Value) + Convert.ToDecimal(row.Cells["nFondoGarantia"].Value)).ToString("N2").Trim() + "</div>"); -- Comentado 20190314, ya viene incluido el fondo garantia desde el query
                            strHTMLContent.Append("<div><b>Importe:</b> " + row.Cells["IdMoneda_tt_Dsc"].Value.ToString().Trim() + " " + (Convert.ToDecimal(row.Cells["nvNegociableInteres"].Value)).ToString("N2").Trim() + "</div>");
                            strHTMLContent.Append("<div><b>Fecha de Vencimiento:</b> " + strFechaVenc + "</div>");
                            strHTMLContent.Append("<div><b>Girador:</b> " + row.Cells["IdSocio_Dsc"].Value.ToString().Trim() + "</div>");
                            strHTMLContent.Append("<div><b>Tipo de Cartera:</b> " + row.Cells["TipoCartera"].Value.ToString().Trim() + "</div>");
                            strHTMLContent.Append("<br>");
                            strHTMLContent.Append("<div style='text-align:center'>CESION DOCUMENTARIA</div>");
                            strHTMLContent.Append("<br>");
                            strHTMLContent.Append("<div>Oficina: Av. El Derby N°254 Of.1106 - Santiago de Surco</div>");
                            strHTMLContent.Append("<div>Atención: L-V 8:30 a 5:00 p.m. Horario Corrido</div>");
                            strHTMLContent.Append("<div>Central Telefónica: 208-5900</div>");
                            strHTMLContent.Append("<div>Email: [email protected] [email protected]</div>");
                            strHTMLContent.Append("</td>");
                            strHTMLContent.Append("<td width='4%'>");
                            strHTMLContent.Append("</td>");
                            strHTMLContent.Append("<td width='48%'>");
                            strHTMLContent.Append("<div style='text-align:center'>AVISO DE VENCIMIENTO</div>");
                            strHTMLContent.Append("<div>");
                            strHTMLContent.Append("<table width='100%' style='font-size: 9px;' border='1' cellpadding='0' cellspacing='0' bordercolor='#000000'>");
                            strHTMLContent.Append("<tr><td colspan='4' align='center'> <b>MONTO ESTIMADO A PAGAR DESPUES DEL VENCIMIENTO </b></td></tr>");
                            strHTMLContent.Append("<tr align='center'><td><b>DIA</b></td><td><b>FECHA VTO.</b></td><td><b>ABONOS/TRANF</b></td><td><b>CON CHEQUE</b></td></tr>");

                            DataSet ds = new DataSet();
                            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionStrDBEfideFactoring"].ConnectionString))
                            {
                                SqlCommand cmd1 = new SqlCommand("Rpt_AvisoCobranza", con);
                                cmd1.CommandType = CommandType.StoredProcedure;
                                cmd1.Parameters.AddWithValue("@IdLote", row.Cells["IdLote"].Value.ToString().Trim());
                                cmd1.Parameters.AddWithValue("@cItem", row.Cells["cItem"].Value.ToString().Trim());
                                cmd1.Parameters.AddWithValue("@Opcion", 1);
                                SqlDataAdapter daCab = new SqlDataAdapter(cmd1);
                                daCab.Fill(ds, "dtAvisoCobranzaCab");
                                con.Close();
                            }


                            int ifilas = 0;
                            foreach (DataRow item in ds.Tables[0].Rows)
                            {
                                strHTMLContent.Append("<tr><td align='center'>" + item["Dia"].ToString() + "</td><td align='center'>" + item["FechaVencimiento"].ToString() + "</td><td align='right'>" + Convert.ToDecimal(item["Abono"]).ToString("N2") + "</td><td align='right'>" + Convert.ToDecimal(item["AbonoCheque"]).ToString("N2") + "</td></tr>");
                                ifilas = ifilas + 1;
                            }

                            for (int i = 1; i <= (9 - ifilas); i++)
                            {
                                strHTMLContent.Append("<tr><td align='center'> &nbsp" + "</td><td align='center'> &nbsp" + "</td><td align='right'> &nbsp" + "</td><td align='right'> &nbsp" + "</td></tr>");
                            }

                            strHTMLContent.Append("</table>");
                            strHTMLContent.Append("</div>");

                            strHTMLContent.Append("<div>- El pago después de la fecha de vencimiento considerará los gastos notariales e intereses y las tasas estarán sujetas a variación.</div>");
                            strHTMLContent.Append("<div>- De acuerdo a lo establecido en el artículo 1257 del Código Civil, los pagos efectuados después de su vencimiento, se aplicarán: 1° A los gastos, 2° A los intereses pactados y 3° al capital.</div>");
                            strHTMLContent.Append("<div>- Prodrá cancelarlo en bancos:</div>");

                            if (row.Cells["IdMoneda_tt_Dsc"].Value.ToString().Trim().Equals("S/.")) //Soles
                            {
                                strHTMLContent.Append("<div style='text-align:center'><b>BCP CTA.CTE. S/. 193-1461392-0-34</b></div>");
                                strHTMLContent.Append("<div style='text-align:center'><b>Scotiabank CTA.CTE. S/. 000-8245959</b></div>");
                            }
                            else //Dolares
                            {
                                strHTMLContent.Append("<div style='text-align:center'><b>BCP CTA.CTE. US$ 193-1471927-1-57</b></div>");
                                strHTMLContent.Append("<div style='text-align:center'><b>Scotiabank CTA.CTE. US$ 000-3730219</b></div>");
                            }

                            strHTMLContent.Append("<div>- Luego de efectuar el abono/tranf debe enviar la boleta via email.</div>");
                            strHTMLContent.Append("<div>- La letra de cambio pasará a protesto al 6to día de su vencimiento.</div>");
                            strHTMLContent.Append("</td>");
                            strHTMLContent.Append("</tr>");
                            strHTMLContent.Append("<br><br><br><br><br> <br><br>");
                            strHTMLContent.Append("</table>");

                            CountRow++;
                        }

                        IdPagadoraOld = row.Cells["IdPagadora"].Value.ToString().Trim();



                        //strHTMLContent.Append("</body></html>");
                        //string strPath = "d:\\" + IdPagadoraOld + ".doc";
                        //FileStream fStream = File.Create(strPath);
                        //fStream.Close();
                        //fStream = null;
                        ////fStream.Dispose();

                        //StreamWriter sWriter = new StreamWriter(strPath);
                        //sWriter.Write(strHTMLContent);
                        //sWriter.Close();
                        //wordDocument = appWord.Documents.Open(@"D:\" + IdPagadoraOld + ".doc");
                        //wordDocument.ExportAsFixedFormat(@"D:\" + IdPagadoraOld + ".pdf", WdExportFormat.wdExportFormatPDF);
                        //appWord.Documents.Close();
                        //appWord = null;
                        //appWord = new Microsoft.Office.Interop.Word.Application();
                    }
                }

                //appWord.Documents.Close();

                if (flg == true)
                {
                    strHTMLContent.Append("</body></html>");
                    string     strPath = "d:\\" + IdPagadoraOld + ".doc";
                    FileStream fStream = File.Create(strPath);
                    fStream.Close();
                    fStream = null;
                    //fStream.Dispose();

                    StreamWriter sWriter = new StreamWriter(strPath);
                    sWriter.Write(strHTMLContent);
                    sWriter.Close();
                    wordDocument = appWord.Documents.Open(@"D:\" + IdPagadoraOld + ".doc");
                    wordDocument.ExportAsFixedFormat(@"D:\" + IdPagadoraOld + ".pdf", WdExportFormat.wdExportFormatPDF);

                    //appWord.Documents.Close(SaveChanges=false);

                    wordDocument.Close(SaveChanges = false);
                    //appWord.Quit(SaveChanges = false);
                    //appWord = null;
                    //appWord = new Word.Application();
                }



                //foreach (Word.Document Doc in appWord.Documents)
                //{
                //    Doc.Close(SaveChanges = false);
                //}

                //appWord.Documents.Close(SaveChanges=false);
                appWord.Quit(SaveChanges = false);
                appWord = null;



                if (appWord != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(appWord);
                }
                appWord = null;
                GC.Collect();

                MessageBox.Show("Se grabo en d:/DocTo.pdf");

                //ProcessStartInfo startInfo = new ProcessStartInfo();
                //startInfo.FileName = "winword.EXE";
                //startInfo.Arguments = "d:\\doc1.doc";
                //Process.Start(startInfo);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #22
0
        public void GenerateWordForLettre(string path, LettreContent lettreContent)
        {
            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);

            Word.Paragraph paragraphEmpty = document.Content.Paragraphs.Add(missing);
            paragraphEmpty.SpaceBefore = 55;
            paragraphEmpty.Range.InsertParagraphAfter();

            Word.Paragraph paragraphTitle = document.Content.Paragraphs.Add(missing);
            paragraphTitle.Range.Text        = "من شركة الوكيل لاستخلاص الديون";
            paragraphTitle.Alignment         = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            paragraphTitle.Range.Font.NameBi = "Arial";
            paragraphTitle.Range.Font.SizeBi = 28;
            paragraphTitle.SpaceAfter        = 50;
            paragraphTitle.Range.InsertParagraphAfter();

            object oEndOfDoc = "\\endofdoc";

            Word.Range tblRange = document.Bookmarks[oEndOfDoc].Range;
            Word.Table table    = document.Tables.Add(tblRange, 2, 3);

            table.Borders.Enable = 0;
            table.Cell(1, 1).Range.ParagraphFormat.BaseLineAlignment = Word.WdBaselineAlignment.wdBaselineAlignFarEast50;
            table.Cell(1, 1).Width           = 70;
            table.Cell(1, 1).Range.Text      = "Nom et prénom:";
            table.Cell(1, 1).Range.Font.Name = "Arial";
            table.Cell(1, 1).Range.Font.Size = 14;
            table.Cell(1, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

            table.Cell(1, 2).Range.ParagraphFormat.BaseLineAlignment = Word.WdBaselineAlignment.wdBaselineAlignFarEast50;
            table.Cell(1, 2).Range.Text      = lettreContent.NomClient;
            table.Cell(1, 2).Width           = 320;
            table.Cell(1, 2).Range.Font.Name = "Arial";
            table.Cell(1, 2).Range.Font.Size = 18;
            table.Cell(1, 2).Range.Font.Bold = 1;
            table.Cell(1, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;

            table.Cell(1, 3).Range.ParagraphFormat.BaseLineAlignment = Word.WdBaselineAlignment.wdBaselineAlignFarEast50;
            table.Cell(1, 3).Width             = 70;
            table.Cell(1, 3).Range.Text        = ":الاسم واللقب";
            table.Cell(1, 3).Range.Font.NameBi = "Arial";
            table.Cell(1, 3).Range.Font.SizeBi = 16;
            table.Cell(1, 3).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

            table.Cell(2, 1).Range.ParagraphFormat.BaseLineAlignment = Word.WdBaselineAlignment.wdBaselineAlignFarEast50;
            table.Cell(2, 1).Width           = 70;
            table.Cell(2, 1).Range.Text      = "Agence:";
            table.Cell(2, 1).Range.Font.Name = "Arial";
            table.Cell(2, 1).Range.Font.Size = 14;
            table.Cell(2, 1).Range.ParagraphFormat.Alignment         = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            table.Cell(2, 2).Range.ParagraphFormat.BaseLineAlignment = Word.WdBaselineAlignment.wdBaselineAlignFarEast50;

            table.Cell(2, 2).Range.Text      = lettreContent.Agence;
            table.Cell(2, 2).Width           = 320;
            table.Cell(2, 2).Range.Font.Name = "Arial";
            table.Cell(2, 2).Range.Font.Size = 18;
            table.Cell(2, 2).Range.Font.Bold = 1;
            table.Cell(2, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;

            table.Cell(2, 3).Range.ParagraphFormat.BaseLineAlignment = Word.WdBaselineAlignment.wdBaselineAlignFarEast50;
            table.Cell(2, 3).Width             = 70;
            table.Cell(2, 3).Range.Text        = ":الفرع";
            table.Cell(2, 3).Range.Font.NameBi = "Arial";
            table.Cell(2, 3).Range.Font.SizeBi = 16;
            table.Cell(2, 3).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

            Word.Paragraph paragraphBody1 = document.Content.Paragraphs.Add(missing);
            paragraphBody1.Range.Text        = "تحية طيبة وبعد";
            paragraphBody1.Alignment         = Word.WdParagraphAlignment.wdAlignParagraphRight;
            paragraphBody1.Range.Font.NameBi = "Arial";
            paragraphBody1.Range.Font.SizeBi = 20;
            paragraphBody1.Range.InsertParagraphAfter();

            Word.Paragraph paragraphBody2 = document.Content.Paragraphs.Add(missing);
            paragraphBody2.Range.Text        = "في إطار تكليفنا لمساعدتكم على التواصل لتسوية وضعية دينكم تجاه مصرف الزيتونة والمتعلق بحسابكم البنكي الخاص، نرجو منكم التوجه إلى الفرع المذكور أعلاه أو الاتصال بالشركة لإيجاد أفضل الحلول المناسبة التي تضمن لكم أحسن طريقة لتطهير دينكم";
            paragraphBody2.Alignment         = Word.WdParagraphAlignment.wdAlignParagraphRight;
            paragraphBody2.Range.Font.NameBi = "Arial";
            paragraphBody2.Range.Font.SizeBi = 20;
            paragraphBody2.Range.InsertParagraphAfter();

            Word.Paragraph footer = document.Content.Paragraphs.Add(missing);
            footer.Range.Text        = "رهاننا وعيكم وحسن تفهمكم";
            footer.Alignment         = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            footer.Range.Font.NameBi = "Arial";
            footer.Range.Font.SizeBi = 20;
            footer.SpaceAfter        = 30;
            footer.Range.InsertParagraphAfter();


            object filename = path;

            document.SaveAs2(ref filename);
            document.Close(ref missing, ref missing, ref missing);
            document = null;
            winword.Quit(ref missing, ref missing, ref missing);
            winword = null;
        }
Пример #23
0
        private string InitRead(string Template, Dictionary <string, string> datas, System.Data.DataTable dt, string userType, string year, string qymc)
        {
            Microsoft.Office.Interop.Word.Application app = null;
            Microsoft.Office.Interop.Word.Document    doc = null;
            //将要导出的新word文件名
            string physicNewFile = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc";

            try
            {
                app         = new Microsoft.Office.Interop.Word.Application();             //创建word应用程序
                app.Visible = false;
                object fileName = System.Windows.Forms.Application.StartupPath + Template; //Year1;//模板文件
                //打开模板文件
                object oMissing = System.Reflection.Missing.Value;
                doc = app.Documents.Open(ref fileName,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);



                object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                foreach (var item in datas)
                {
                    app.Selection.Find.Replacement.ClearFormatting();
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Text             = item.Key;   //需要被替换的文本
                    app.Selection.Find.Replacement.Text = item.Value; //替换文本

                    //执行替换操作
                    app.Selection.Find.Execute(
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing, ref oMissing,
                        ref oMissing, ref replace,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing);
                }

                object unit;
                unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
                app.Selection.EndKey(ref unit, ref oMissing);
                app.Selection.TypeParagraph(); //插入段落

                if (userType == "C")           //国产
                {
                    app.Selection.Text = String.Format("{0}年{1}企业国产乘用车产品燃料消耗量", year.Substring(0, 4), qymc);
                    Word.Range range = doc.Paragraphs.Last.Range;
                    Microsoft.Office.Interop.Word.Table table = app.Selection.Tables.Add(range, dt.Rows.Count + 1, 12, ref oMissing, ref oMissing);
                    //设置表格的字体大小粗细
                    table.Range.Font.Size = 10;
                    table.Range.Font.Bold = 0;
                    //为表格划线
                    range.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle        = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle       = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle      = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle     = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle   = WdLineStyle.wdLineStyleSingle;

                    //设置表格标题
                    table.Cell(1, 1).Range.Text  = "序号";
                    table.Cell(1, 2).Range.Text  = "汽车生产企业";
                    table.Cell(1, 3).Range.Text  = "车辆型号";
                    table.Cell(1, 4).Range.Text  = "燃料种类";
                    table.Cell(1, 5).Range.Text  = "整车整备质量";
                    table.Cell(1, 6).Range.Text  = "变速器型式";
                    table.Cell(1, 7).Range.Text  = "座位排数";
                    table.Cell(1, 8).Range.Text  = "纯电动驱动模式综合工况续驶里程";
                    table.Cell(1, 9).Range.Text  = "车型燃料消耗量目标值①";
                    table.Cell(1, 10).Range.Text = "综合工况燃烧消耗量实际值②";
                    table.Cell(1, 11).Range.Text = "实际生产量③";
                    table.Cell(1, 12).Range.Text = "备注";

                    //循环数据创建数据行
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        table.Cell(i + 2, 1).Range.Text  = (i + 1).ToString();
                        table.Cell(i + 2, 2).Range.Text  = dt.Rows[i]["Qcscqy"].ToString();
                        table.Cell(i + 2, 3).Range.Text  = dt.Rows[i]["Clxh"].ToString();
                        table.Cell(i + 2, 4).Range.Text  = dt.Rows[i]["Rllx"].ToString();
                        table.Cell(i + 2, 5).Range.Text  = dt.Rows[i]["Zczbzl"].ToString();
                        table.Cell(i + 2, 6).Range.Text  = dt.Rows[i]["Bsqxs"].ToString();
                        table.Cell(i + 2, 7).Range.Text  = dt.Rows[i]["Zwps"].ToString();
                        table.Cell(i + 2, 8).Range.Text  = dt.Rows[i]["Zhgkxslc"].ToString();
                        table.Cell(i + 2, 9).Range.Text  = dt.Rows[i]["TgtZhgkrlxhl"].ToString();
                        table.Cell(i + 2, 10).Range.Text = dt.Rows[i]["ActZhgkrlxhl"].ToString();
                        table.Cell(i + 2, 11).Range.Text = dt.Rows[i]["Sl_act"].ToString();
                    }
                }
                else  //进口
                {
                    app.Selection.Text = String.Format("{0}年{1}企业进口乘用车产品燃料消耗量", year.Substring(0, 4), qymc);
                    Word.Range range = doc.Paragraphs.Last.Range;
                    Microsoft.Office.Interop.Word.Table table = app.Selection.Tables.Add(range, dt.Rows.Count + 1, 12, ref oMissing, ref oMissing);
                    //设置表格的字体大小粗细
                    table.Range.Font.Size = 10;
                    table.Range.Font.Bold = 0;
                    //为表格划线
                    range.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle        = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle       = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle      = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle     = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle   = WdLineStyle.wdLineStyleSingle;

                    //设置表格标题
                    table.Cell(1, 1).Range.Text  = "序号";
                    table.Cell(1, 2).Range.Text  = "汽车生产企业";
                    table.Cell(1, 3).Range.Text  = "车辆型号";
                    table.Cell(1, 4).Range.Text  = "燃料种类";
                    table.Cell(1, 5).Range.Text  = "整车整备质量";
                    table.Cell(1, 6).Range.Text  = "变速器型式";
                    table.Cell(1, 7).Range.Text  = "座位排数";
                    table.Cell(1, 8).Range.Text  = "纯电动驱动模式综合工况续驶里程";
                    table.Cell(1, 9).Range.Text  = "车型燃料消耗量目标值①";
                    table.Cell(1, 10).Range.Text = "综合工况燃烧消耗量实际值②";
                    table.Cell(1, 11).Range.Text = "实际生产量③";
                    table.Cell(1, 12).Range.Text = "备注";

                    //循环数据创建数据行
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        table.Cell(i + 2, 1).Range.Text  = (i + 1).ToString();
                        table.Cell(i + 2, 2).Range.Text  = dt.Rows[i]["Qcscqy"].ToString();
                        table.Cell(i + 2, 3).Range.Text  = dt.Rows[i]["Clxh"].ToString();
                        table.Cell(i + 2, 4).Range.Text  = dt.Rows[i]["Rllx"].ToString();
                        table.Cell(i + 2, 5).Range.Text  = dt.Rows[i]["Zczbzl"].ToString();
                        table.Cell(i + 2, 6).Range.Text  = dt.Rows[i]["Bsqxs"].ToString();
                        table.Cell(i + 2, 7).Range.Text  = dt.Rows[i]["Zwps"].ToString();
                        table.Cell(i + 2, 8).Range.Text  = dt.Rows[i]["Zhgkxslc"].ToString();
                        table.Cell(i + 2, 9).Range.Text  = dt.Rows[i]["TgtZhgkrlxhl"].ToString();
                        table.Cell(i + 2, 10).Range.Text = dt.Rows[i]["ActZhgkrlxhl"].ToString();
                        table.Cell(i + 2, 11).Range.Text = dt.Rows[i]["Sl_act"].ToString();
                    }
                }

                unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
                app.Selection.EndKey(ref unit, ref oMissing);
                app.Selection.TypeParagraph();//插入段落


                app.Selection.Text = @"注:①车型燃料消耗量目标值,同一车辆型号因整车整备质量、座位排数、变速器形式不同有多个不同的燃料消耗量目标值时,计算企业平均消耗量目标值时采用最小的燃料消耗量目标值。
②综合工况燃料消耗量实际值,四舍五入至小数点后一位;如汽车燃料消耗量通告系统中同一车型有多个不同的综合工况燃料消耗量实际值,则填写该车型最高的综合工况燃料消耗量实际值。
③实际生产量/实际进口量,不含出口量。";


                //对替换好的word模板另存为一个新的word文档
                doc.SaveAs(System.Windows.Forms.Application.StartupPath + "\\ExcelHeaderTemplate\\" + physicNewFile,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

                //准备导出word
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭word文档
                }
                if (app != null)
                {
                    app.Quit();//退出word应用程序
                }
            }
            return(physicNewFile);
        }
Пример #24
0
        //生成word文档
        void ExpWordByWord()
        {
            Word._Application app = new Word.Application();
            //表示System.Type信息中的缺少值
            object nothing = Type.Missing;

            try
            {
                //高考卡号
                string            strKaHao       = "";
                Entity.GaoKaoCard infoGaoKaoCard = DAL.GaoKaoCard.GaoKaoCardEntityGetByStudentId(userinfo.StudentId);
                if (infoGaoKaoCard != null)
                {
                    strKaHao = infoGaoKaoCard.KaHao;
                }
                //省份名称
                string strProvinceName = userinfo.ProvinceName;

                //读取模板文件
                object temp = System.Web.HttpContext.Current.Server.MapPath("~/CePing/职业兴趣模板.doc");//读取模板文件

                //建立一个基于摸版的文档
                Word._Document doc = app.Documents.Add(ref temp, ref nothing, ref nothing, ref nothing);
                //学生基本信息
                Word.Table tb1 = doc.Tables[1];
                if (tb1.Rows.Count == 4)
                {
                    //在指定单元格填值
                    //第1行
                    tb1.Cell(1, 2).Range.Text = userinfo.StudentName;
                    tb1.Cell(1, 4).Range.Text = (user.Sex == 1 ? "女" : "男");
                    //第2行
                    tb1.Cell(2, 2).Range.Text = user.SchoolName;
                    tb1.Cell(2, 4).Range.Text = (userinfo.KeLei == 1 ? "文史" : "理工");
                    //第3行
                    tb1.Cell(3, 2).Range.Text = strProvinceName;
                    tb1.Cell(3, 4).Range.Text = user.GKYear.ToString();
                    //第4行
                    tb1.Cell(4, 2).Range.Text = strKaHao;
                    tb1.Cell(4, 4).Range.Text = Basic.TypeConverter.StrToDateStr(DateTime.Now.ToString());
                }

                //插入图片
                Word.Table tb2              = doc.Tables[2];
                string     path             = AppDomain.CurrentDomain.BaseDirectory + ("CePing/ImgOfResult/Holland/") + user.StudentId + "_holland.jpg";
                string     FileName         = path;//@"C:\chart.jpeg";//图片所在路径
                object     LinkToFile       = false;
                object     SaveWithDocument = true;
                object     Anchor           = tb2.Range;
                doc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
                //doc.Application.ActiveDocument.InlineShapes[1].Width = 300f;//图片宽度
                //doc.Application.ActiveDocument.InlineShapes[1].Height = 200f;//图片高度

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

                //职业兴趣测评分类说明
                Word.Table tb3 = doc.Tables[3];
                if (tb3.Rows.Count == 7)
                {
                    //在指定单元格填值
                    //第2行 现实
                    tb3.Cell(2, 2).Range.Text = intReality.ToString();
                    tb3.Cell(2, 3).Range.Text = Level(intReality);
                    //第3行 研究
                    tb3.Cell(3, 2).Range.Text = intStudy.ToString();
                    tb3.Cell(3, 3).Range.Text = Level(intStudy);
                    //第4行 艺术
                    tb3.Cell(4, 2).Range.Text = intArt.ToString();
                    tb3.Cell(4, 3).Range.Text = Level(intArt);
                    //第5行 社会
                    tb3.Cell(5, 2).Range.Text = intSociety.ToString();
                    tb3.Cell(5, 3).Range.Text = Level(intSociety);
                    //第6行 企业
                    tb3.Cell(6, 2).Range.Text = intBusiness.ToString();
                    tb3.Cell(6, 3).Range.Text = Level(intBusiness);
                    //第7行 常规
                    tb3.Cell(7, 2).Range.Text = intTradition.ToString();
                    tb3.Cell(7, 3).Range.Text = Level(intTradition);
                }


                //模板中 占位符的替换
                Microsoft.Office.Interop.Word.Document oDoc = (Microsoft.Office.Interop.Word.Document)doc;
                bb();
                //根据你最强的兴趣,可见你的特点是
                ReplaceZF(oDoc, "@xqlx", strTeDian, Type.Missing);
                //你可能喜欢的专业
                for (int i = 0; i < arrTuiJianZhuanYe.Length; i++)
                {
                    ReplaceZF(oDoc, "@xihuanzhuanye" + i, arrTuiJianZhuanYe[i], Type.Missing);
                }
                if (arrTuiJianZhuanYe.Length < 6)
                {
                    for (int i = arrTuiJianZhuanYe.Length; i < 6; i++)
                    {
                        ReplaceZF(oDoc, "@xihuanzhuanye" + i, "", Type.Missing);
                    }
                }

                //不建议选择的专业范围
                for (int i = 0; i < arrBuTuiJianZhuanYe.Length; i++)
                {
                    ReplaceZF(oDoc, "@buxihuanzhuanye" + i, arrBuTuiJianZhuanYe[i], Type.Missing);
                }
                if (arrBuTuiJianZhuanYe.Length < 6)
                {
                    for (int i = arrBuTuiJianZhuanYe.Length; i < 6; i++)
                    {
                        ReplaceZF(oDoc, "@buxihuanzhuanye" + i, "", Type.Missing);
                    }
                }


                //保存到服务器
                object fileName = System.Web.HttpContext.Current.Server.MapPath("~/") + "CePing/ImgOfResult/Holland/" + strKaHao + "(" + userinfo.StudentName + "_" + userinfo.StudentId + ")" + "_职业兴趣测评.doc";//获取服务器路径
                //保存doc文档
                oDoc.SaveAs(ref fileName, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                            ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                            ref nothing, ref nothing, ref nothing);
                oDoc.Close(ref nothing, ref nothing, ref nothing);
                app.Quit(ref nothing, ref nothing, ref nothing);

                //输出word
                ExtWord(fileName.ToString(), "ts.doc");
            }
            catch (Exception ex)
            {
                //  resultMsg = "导出错误:" + ex.Message;
                app.Quit(ref nothing, ref nothing, ref nothing);
            }
        }
Пример #25
0
        private void createWords()
        {
            int filesToCreateTemp = frm1.filesToCreate;             // avoid change in '#files to be created' during runtime

            try
            {
                string workingDir = frm1.workingDirectory + "officeSimulation_word\\";
                System.IO.Directory.CreateDirectory(workingDir);
                int    documentCount    = 0;
                string wordFileNameDate = frm1.wordFileName + DateTime.Now.ToString("dd-MM-yyyy_HH-mm");
                string wordFileNameDateFinal;

                // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Word instance ~~~~~~~~~~~~~~~~~~~~~~~~~
                var winword = new Microsoft.Office.Interop.Word.Application();
                winword.ShowAnimation = false;
                winword.Visible       = false;
                object winWordMissing = System.Reflection.Missing.Value;
                // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

                while (documentCount < filesToCreateTemp)
                {
                    wordFileNameDateFinal = wordFileNameDate + "_" + documentCount;
                    // ~~~~~~ create word files (vary formatting)
                    try
                    {
                        if (frm1.varyFormatting)
                        {
                            //Selecting random lorem text length
                            Random r       = new Random(DateTime.Now.Millisecond);
                            int    rLorem1 = r.Next(0, 5);
                            int    rLorem2 = r.Next(0, 5);
                            int    rLorem3 = r.Next(0, 5);
                            int    rLorem4 = r.Next(0, 2);
                            int    rLorem5 = r.Next(0, 2);

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

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

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

                            //adding text to document
                            document.Content.SetRange(0, 0);
                            document.Content.Text = frm1.lorems[rLorem1] + "\r\n";
                            // adding some delay
                            if (frm1.addDelay)
                            {
                                Thread.Sleep(frm1.addDelaySec * 1000);
                            }
                            document.Content.Text = frm1.lorems[rLorem2] + "\r\n";
                            document.Content.Text = frm1.lorems[rLorem3];

                            //Add paragraph with Heading 1 style
                            Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref winWordMissing);
                            object styleHeading1 = "Heading 1";
                            para1.Range.set_Style(ref styleHeading1);
                            para1.Range.Text = frm1.lorems[rLorem1];
                            para1.Range.InsertParagraphAfter();

                            //Add paragraph with Heading 2 style
                            Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref winWordMissing);
                            object styleHeading2 = "Heading 2";
                            para2.Range.set_Style(ref styleHeading2);
                            para2.Range.Text = frm1.lorems[rLorem2];
                            para2.Range.InsertParagraphAfter();

                            //Save the document
                            object filename = workingDir + wordFileNameDateFinal + ".docx";
                            //object filename = filePath + "\\" + fileName + ".docx";
                            document.SaveAs2(ref filename);
                            // Keeping a list of files created
                            frm1.listOfWordFiles.Add(filename.ToString());
                            document.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                            document = null;
                            if (document != null)
                            {
                                Marshal.ReleaseComObject(document);
                            }
                        }
                        else // ~~~~~~ create word files (NO formatting)
                        {
                            //adding text to document
                            Random r       = new Random(DateTime.Now.Millisecond);
                            int    rLorem1 = r.Next(0, 5);
                            int    rLorem2 = r.Next(0, 5);
                            int    rLorem3 = r.Next(0, 5);

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

                            document.Content.SetRange(0, 0);
                            document.Content.Text = frm1.lorems[rLorem1] + "\r\n";
                            // adding some delay
                            if (frm1.addDelay)
                            {
                                Thread.Sleep(frm1.addDelaySec * 1000);
                            }
                            document.Content.Text = frm1.lorems[rLorem2] + "\r\n";
                            document.Content.Text = frm1.lorems[rLorem3];

                            //Save the document
                            object filename = workingDir + wordFileNameDateFinal + ".docx";
                            //object filename = filePath + "\\" + fileName + ".docx";
                            document.SaveAs2(ref filename);
                            // Keeping a list of files created
                            frm1.listOfWordFiles.Add(filename.ToString());
                            document.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                            document = null;
                            if (document != null)
                            {
                                Marshal.ReleaseComObject(document);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error creating Word file!");
                        Console.WriteLine(ex.Message);
                    }
                    documentCount++;
                }

                // ~~~~~~ copy some of the documents
                int i2 = 0;
                while (i2 < filesToCreateTemp)
                {
                    if (i2 % 4 == 0)
                    {
                        string filePathNoExtension = frm1.listOfWordFiles[i2].Substring(0, frm1.listOfWordFiles[i2].Length - 5);
                        string newFilePathCopy     = filePathNoExtension + "_copy" + ".docx";
                        try
                        {
                            var originalDocument = winword.Documents.Open(frm1.listOfWordFiles[i2]); // Open original document

                            originalDocument.ActiveWindow.Selection.WholeStory();                    // Select all in original document
                            var originalText = originalDocument.ActiveWindow.Selection;              // Copy everything to the variable

                            var newDocument          = new Word.Document();                          // Create new Word document
                            newDocument.Range().Text = originalText.Text;                            // Pasete everything from the variable
                            newDocument.SaveAs(newFilePathCopy);                                     // maybe SaveAs2??                  // Save the new document

                            originalDocument.Close(false);
                            newDocument.Close();

                            if (originalDocument != null)
                            {
                                Marshal.ReleaseComObject(originalDocument);
                            }
                            if (newDocument != null)
                            {
                                Marshal.ReleaseComObject(newDocument);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error coping documents");
                            Console.WriteLine(ex.Message);
                        }
                    }
                    i2++;
                }

                // ~~~~~~ find-replace in some documents
                int i3 = 0;
                while (i3 < filesToCreateTemp)
                {
                    if (i3 % 3 == 0)
                    {
                        try
                        {
                            Microsoft.Office.Interop.Word.Document aDoc = winword.Documents.Open(frm1.listOfWordFiles[i3], ReadOnly: false, Visible: false);
                            aDoc.Activate();

                            winword.Selection.Find.Execute(frm1.textToSearch1, false, true, false, false, false, true, 1, false, frm1.textToReplace1, 2, false, false, false, false);
                            winword.Selection.Find.Execute(frm1.textToSearch2, false, true, false, false, false, true, 1, false, frm1.textToReplace2, 2, false, false, false, false);

                            aDoc.SaveAs2();

                            aDoc.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                            aDoc = null;
                            if (aDoc != null)
                            {
                                Marshal.ReleaseComObject(aDoc);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error in find-replace");
                            Console.WriteLine(ex.Message);
                        }
                    }
                    i3++;
                }

                // ~~~~~~~~~~~~~~~~~~~~ Terminating Word instance ~~~~~~~~~~~~~~~~~~~
                winword.Quit(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                winword.Quit();
                if (winword != null)
                {
                    Marshal.ReleaseComObject(winword);
                }
                winword        = null;
                winWordMissing = null;
                // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            }
            catch (Exception ex)
            {
                Console.WriteLine("backGroundWorker WordCreate Error");
                Console.WriteLine(ex.Message);
            }

            tskCreateWordsRunning = false;
            Console.WriteLine();
            Console.WriteLine("runEverything(): createWords() -> DONE");
        }
Пример #26
0
        private void thesisProcess_DoWork(object sender, DoWorkEventArgs e)        //Thread start edildiğinde bu fonksiyona girer.
        {
            int failCount = 0;

            thesisProcess.ReportProgress(1);            //Yüzdeyi göstermek için kullandığımız method ReportProgres(x) x sinyalini gönderir.

            Microsoft.Office.Interop.Word.Application app = new Word.Application();
            Microsoft.Office.Interop.Word.Document    doc = app.Documents.Open(txt_thesispath.Text);         //Yukarda seçilen dosyayı Document objesinin içine yükleme işlemi.
            Word.WdStatistic stat    = Word.WdStatistic.wdStatisticPages;
            object           missing = System.Reflection.Missing.Value;
            int pageCountNumber      = doc.ComputeStatistics(stat, ref missing); //Sayfa sayısını num değişkenine atıyoruz.

            thesisProcess.ReportProgress(3);                                     //Yüzde 3

            //İlk sayfa sayısını kontrol ediyoruz.
            if (pageCountNumber < 40 || pageCountNumber > 180)
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("İdeal tez uzunluğu 40 - 180 sayfa arasında olmalıdır! Mevcut sayfa sayısı:" + pageCountNumber);
                }));
            }

            float leftmargin   = doc.PageSetup.LeftMargin;   //Sol boşluk,
            float rightmargin  = doc.PageSetup.RightMargin;  //Sağ boşluk,
            float topMargin    = doc.PageSetup.TopMargin;    //Üst boşluk,
            float bottomMargin = doc.PageSetup.BottomMargin; //Alt boşluk değerleri dokümandan okunuyor.

            if (rightmargin != 70.9f)                        //Sağ boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Sağ kenar boşluğu 2.5 cm olmalıdır!");
                }));
            }

            if (bottomMargin != 70.9f)            //Alt boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Alt kenar boşluğu 2.5 cm olmalıdır!");
                }));
            }

            if (leftmargin != 92.15f)            //Sol boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Sol kenar boşluğu 3.25 cm olmalıdır!");
                }));
            }

            if (topMargin != 85.05f)            //Üst boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Üst kenar boşluğu 3.0 cm olmalıdır!");
                }));
            }
            thesisProcess.ReportProgress(5);

            int paragraphcount = doc.Paragraphs.Count;

            int counter            = 0;
            int timesnewromancount = 0;
            int elevenpuntocounter = 0;

            bool onsozexists      = false;
            bool icindekilerexist = false;
            bool ozetexists       = false;
            bool kaynakExists     = false;
            bool beyanexists      = false;


            bool abstractExists              = false;
            bool sekilListesiexists          = false;
            bool eklerlistesiexists          = false;
            bool simgelerveKisaltmalarExists = false;

            int ShapesCount   = doc.InlineShapes.Count;
            int inShapesCount = doc.Shapes.Count;

            int tablocount = 0;

            int sekilcount = 0;

            Hashtable htSekil = new Hashtable();
            Hashtable htTablo = new Hashtable();

            double sekilCounter = 0;
            double tabloCounter = 0;

            foreach (Paragraph objParagraph in doc.Paragraphs)               //Paragrafların her biri tek tek okunup objParagraph objesinin içine atılıyor.
            {
                if (objParagraph.Range.Font.Name == "Times New Roman")       //Eğer font Times New Roman ise;
                {
                    timesnewromancount++;                                    //Times New Roman sayısı bir arttırılıyor.
                }
                if (objParagraph.Range.Font.Size == 11)                      //Font size'ı 11 ise;
                {
                    elevenpuntocounter++;                                    //Font size'ı kontrol eden değişkenimiz bir arttırılıyor.
                }
                if (objParagraph.Range.Text.Trim() == Constants.ICINDEKILER) //İçindekiler texti paragrafta bulundu mu?
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ICINDEKILER);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ICINDEKILER) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ICINDEKILER) + Constants.ICINDEKILER.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'İÇİNDEKİLER'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'İÇİNDEKİLER'");                            //Hata ekrana bastırılır..
                        }));
                    }

                    icindekilerexist = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.OZET)               //Özet texti
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.OZET);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.OZET) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.OZET) + Constants.OZET.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'Özet'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'Özet'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    ozetexists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.ONSOZ)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ONSOZ);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ONSOZ) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ONSOZ) + Constants.ONSOZ.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'ÖNSÖZ'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'ÖNSÖZ'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    onsozexists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.KAYNAKLAR)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.KAYNAKLAR);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.KAYNAKLAR) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.KAYNAKLAR) + Constants.KAYNAKLAR.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'KAYNAKLAR'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'KAYNAKLAR'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    kaynakExists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.ABSTRACT)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ABSTRACT);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ABSTRACT) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ABSTRACT) + Constants.ABSTRACT.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'ABSTRACT'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'ABSTRACT'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    abstractExists = true;
                }

                if (objParagraph.Range.Text.Trim() == Constants.BEYAN)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.BEYAN);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.BEYAN) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.BEYAN) + Constants.BEYAN.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;
                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'BEYAN'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'BEYAN'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    beyanexists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.SEKILLERLISTESI)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKILLERLISTESI);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKILLERLISTESI) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKILLERLISTESI) + Constants.SEKILLERLISTESI.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;
                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'ŞEKİLLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'ŞEKİLLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    sekilListesiexists = true;
                }

                if (objParagraph.Range.Text.Trim() == Constants.EKLERLISTESI)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.EKLERLISTESI);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.EKLERLISTESI) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.EKLERLISTESI) + Constants.EKLERLISTESI.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'EKLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'EKLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    eklerlistesiexists = true;
                }

                if (objParagraph.Range.Text.Trim() == Constants.SIMGELERVEKISALTMALAR)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SIMGELERVEKISALTMALAR);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SIMGELERVEKISALTMALAR) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SIMGELERVEKISALTMALAR) + Constants.SIMGELERVEKISALTMALAR.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'SİMGELER VE KISALTMALAR'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'SİMGELER VE KISALTMALAR'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    simgelerveKisaltmalarExists = true;
                }

                if (objParagraph.Range.Text.Contains(Constants.SEKIL))
                {
                    //Şekil 2.3.
                    object     start      = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKIL);
                    object     end        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKIL) + Constants.SEKIL.Length + 5;
                    Word.Range rangesekil = doc.Range(ref start, ref end);

                    bool isSekild = Helper.TextIsSekil(rangesekil.Text);

                    if (isSekild && !htSekil.ContainsKey(rangesekil.Text))                  //Eğer hashtable'da şekil yoksa kontrolü yapılıyor.
                    {
                        sekilcount++;                                                       //Yoksa şekil sayacı bir arttırılıyor.
                        htSekil[rangesekil] = rangesekil.Text;                              //Hashtable'ın içine şekil atılıyor.

                        double sekilNumber = Double.Parse(rangesekil.Text.Substring(6, 3)); // 4.3

                        if (sekilNumber < sekilCounter)                                     //sekilCounter en son şeklin numarasını tutar. Eğer yeni gelen şekil son şekilden küçükse hata vardır.
                        {
                            failCount++;
                            this.Invoke(new MethodInvoker(() =>
                            {
                                this.listResults.Items.Add("Şekil numaraları sırayla olmalıdır!");                                //Hata ekrana bastırılır..
                            }));
                        }
                        else
                        {
                            sekilCounter = sekilNumber;
                        }
                    }

                    if (isSekild && rangesekil.Font.Size < 10)                    //Eğer şekil gelmiş ve font size'ı 10'dan küçükse ekrana hata bastırılır.
                    {
                        failCount++;

                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Şekil kısımları en az 10 boyutunda olmalı!");
                        }));
                    }
                }
                //BEYAN
                if (objParagraph.Range.Text.Contains(Constants.TABLO))                //Şekil için yapılan yukardaki bloğun tamamı tablo için de yapılıyor.
                {
                    object     start      = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.TABLO);
                    object     end        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.TABLO) + Constants.TABLO.Length + 5;
                    Word.Range rangetablo = doc.Range(ref start, ref end);

                    bool istablo = Helper.TextIsTablo(rangetablo.Text);
                    if (istablo && !htTablo.ContainsKey(rangetablo.Text))
                    {
                        tablocount++;
                        htTablo[rangetablo] = rangetablo.Text;
                    }

                    if (istablo && rangetablo.Font.Size < 10)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Tablo kısımları en az 10 boyutunda olmalı!");
                        }));
                    }
                }

                thesisProcess.ReportProgress(5 + (95 * counter / doc.Paragraphs.Count));            // Progress hesaplama yüzde hesaplama Toplam paragraf sayısının mevcut paragraf indexine oranını buluyoruz. Bunu yüzde olarak gösteriyoruz.

                counter++;
            }


            if ((ShapesCount + inShapesCount) < (tablocount + sekilcount)) //Eğer dokümandaki shape countu tablo ve şekil count'ından küçükse o zaman tüm tablo ve şekillere isim verilmemiştir anlamına gelir.
            {                                                              //Bu durumda ekrana hata bastırılır.
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tüm şekil ve tabloların altına Şekil ve Tablo numarası yazılmalıdır!");
                }));
            }

            if (!beyanexists)            //Yukarıdaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("BEYAN bölümü eksik!");
                }));
            }
            if (!onsozexists) //Önsöz değişkenine yukarıda atama yapıldı. Eğer atamalar sonucunda değişken true'ya çevrilmemişse;
            {                 //bu kod işler.
                failCount++;  //fail sayısı bir arttırılır.

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ÖNSÖZ bölümü eksik!");                    // Önsöz bölümü eksik hatası ekrana bastırılır.
                }));
            }
            if (!icindekilerexist) //Eğer içindekiler değişkenine true atanmadıysa;
            {                      //hata ekrana bastırılır.
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("İÇİNDEKİLER bölümü eksik!");
                }));
            }
            if (!ozetexists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ÖZET bölümü eksik!");
                }));
            }
            if (!abstractExists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ABSTRACT bölümü eksik!");
                }));
            }


            if (!sekilListesiexists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ŞEKİLLER LİSTESİ bölümü eksik!");
                }));
            }
            if (!eklerlistesiexists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("EKLER LİSTESİ bölümü eksik!");
                }));
            }



            if (!simgelerveKisaltmalarExists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("SIMGELER VE KISALTMALAR bölümü eksik!");
                }));
            }
            if (!kaynakExists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("KAYNAKLAR bölümü eksik!");
                }));
            }
            if (timesnewromancount * 2 < paragraphcount)            //Eğer tezin yarısından çoğu Times New Roman ile yazılmamışsa ekrana hata bastırılır.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tezin yazım fontu Times New Roman olmalıdır! Tezdeki Times New Roman oranı = %" + 100 * timesnewromancount / paragraphcount);
                }));
            }

            if (elevenpuntocounter * 1.5 < paragraphcount)            //Tez içeriğindeki yazıların boyutu 11 punto olmalıdır.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tezin font büyüklüğü 11 punto olmalıdır! Tezde bulunan 11 punto oranı= %" + 100 * elevenpuntocounter / paragraphcount);
                }));
            }


            if (failCount == 0)            //Eğer hata sayısı 0 ise tezinizde hata bulunamadı diye mesaj gösteriyoruz.
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tezinizde hiçbir hata bulunamadı!");
                }));
            }
            else
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add(string.Format("Tezinizde bulunan hata başlığı sayısı:{0}", failCount));                   //Hata sayısı 0'dan farklıysa da tezde bulunan toplam hata sayısı gösteriliyor.
                }));
            }

            doc.Close();
            doc = null;
            //return num;
        }
Пример #27
0
        public void InitRead(string Template, Dictionary <string, string> datas, string saveFileName, DataView dv)
        {
            Microsoft.Office.Interop.Word.Application app = null;
            Microsoft.Office.Interop.Word.Document    doc = null;

            try
            {
                app = new Microsoft.Office.Interop.Word.Application();                     //创建word应用程序
                object fileName = System.Windows.Forms.Application.StartupPath + Template; //Year1;//模板文件
                app.Visible = false;
                //打开模板文件
                object oMissing = System.Reflection.Missing.Value;
                doc = app.Documents.Open(ref fileName,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                foreach (var item in datas)
                {
                    app.Selection.Find.Replacement.ClearFormatting();
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Text             = item.Key;   //需要被替换的文本
                    app.Selection.Find.Replacement.Text = item.Value; //替换文本

                    //执行替换操作
                    app.Selection.Find.Execute(
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing, ref oMissing,
                        ref oMissing, ref replace,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing);
                }
                string imageName = downLoadSignature();
                //电子签章是否存在
                if (!string.IsNullOrEmpty(imageName))
                {
                    //标签
                    object bookMark = "SIGNATURE";
                    if (app.ActiveDocument.Bookmarks.Exists(Convert.ToString(bookMark)) == true)
                    {
                        //图片
                        string replacePic = String.Format(@"{0}\{1}", defaultDirectory.Signature, imageName);
                        //定义该插入图片是否为外部链接
                        object linkToFile = true;
                        //定义插入图片是否随word文档一起保存
                        object saveWithDocument = true;
                        object Nothing          = System.Reflection.Missing.Value;
                        //查找书签
                        app.ActiveDocument.Bookmarks.get_Item(ref bookMark).Select();
                        //设置图片位置
                        app.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                        //在书签的位置添加图片
                        InlineShape inlineShape = app.Selection.InlineShapes.AddPicture(replacePic, ref linkToFile, ref saveWithDocument, ref Nothing);
                        //设置图片大小
                        inlineShape.Width  = 100;
                        inlineShape.Height = 100;
                    }
                }
                System.Data.DataView dt = dv;


                object     tmp   = "BT_CREATE";                                          //WORD中创建标签
                Word.Range range = app.ActiveDocument.Bookmarks.get_Item(ref tmp).Range; //查找标签位置
                Microsoft.Office.Interop.Word.Table table = app.Selection.Tables.Add(range, dt.Table.Rows.Count + 1, 10, ref oMissing, ref oMissing);

                //设置表格的字体大小粗细
                table.Range.Font.Size = 10;
                table.Range.Font.Bold = 0;

                //设置表格标题
                int rowIndex = 1;
                table.Cell(rowIndex, 1).Range.Text  = "序号";
                table.Cell(rowIndex, 2).Range.Text  = "备案号(VIN)";
                table.Cell(rowIndex, 3).Range.Text  = "产品型号";
                table.Cell(rowIndex, 4).Range.Text  = "通用名称";
                table.Cell(rowIndex, 5).Range.Text  = "燃料种类";
                table.Cell(rowIndex, 6).Range.Text  = "燃料消耗量(综合)";
                table.Cell(rowIndex, 7).Range.Text  = "整备质量";
                table.Cell(rowIndex, 8).Range.Text  = "变速器型式";
                table.Cell(rowIndex, 9).Range.Text  = "座椅排数";
                table.Cell(rowIndex, 10).Range.Text = "操作类型";


                //循环数据创建数据行

                foreach (DataRow r in dt.Table.Rows)
                {
                    rowIndex++;
                    table.Cell(rowIndex, 1).Range.Text = (rowIndex - 1).ToString();
                    for (int i = 2; i < 10; i++)
                    {
                        table.Cell(rowIndex, i).Range.Text = Convert.ToString(r[i - 1]);
                    }
                    table.Cell(rowIndex, 10).Range.Text = Convert.ToString(r["APPLYTYPE"]);
                }

                //为表格划线
                range.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle        = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle       = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle      = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle     = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
                range.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle   = WdLineStyle.wdLineStyleSingle;


                //对替换好的word模板另存为一个新的word文档
                doc.SaveAs(saveFileName,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

                //准备导出word
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭word文档
                }
                if (app != null)
                {
                    app.Quit();//退出word应用程序
                }
            }
        }
Пример #28
0
        private void CreateDocument()
        {
            try
            {
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();


                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      = "Header text goes here";
                }

                foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                {
                    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
                    footerRange.Font.Size                 = 10;
                    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    footerRange.Text = "Footer text goes here";
                }

                document.Content.SetRange(0, 0);
                document.Content.Text = "This is test document " + Environment.NewLine;

                Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
                object styleHeading1 = "Heading 1";
                para1.Range.set_Style(ref styleHeading1);
                para1.Range.Text = "Para 1 text";
                para1.Range.InsertParagraphAfter();

                Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
                object styleHeading2 = "Heading 2";
                para2.Range.set_Style(ref styleHeading2);
                para2.Range.Text = "Neve: #NEV#";
                para2.Range.InsertParagraphAfter();

                Word.Table firstTable = document.Tables.Add(para1.Range, 3, 2, ref missing, ref missing);

                firstTable.Borders.Enable = 1;
                foreach (Row row in firstTable.Rows)
                {
                    foreach (Cell cell in row.Cells)
                    {
                        if (cell.RowIndex == 1)
                        {
                            cell.Range.Text      = "Column " + cell.ColumnIndex.ToString();
                            cell.Range.Font.Bold = 1;
                            cell.Range.Font.Name = "verdana";
                            cell.Range.Font.Size = 10;
                            cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                            cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                        }
                        else
                        {
                            cell.Range.Text = "Tartalom " + (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
                        }
                    }
                }

                object filename = @"d:\temp1.docx";
                document.SaveAs(ref filename);
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;
                System.Windows.Forms.MessageBox.Show("Document created successfully !");
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }