/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAceptar_Click(object sender, EventArgs e) { if (ParentForm != null) ParentForm.DialogResult = DialogResult.OK; object oMissing = Missing.Value; String nombreTemplate = String.Format("{0}\\Templates\\{1}", Application.StartupPath, txtDescTemplate.Text); // Abre el Word _Application oWordApp = new Microsoft.Office.Interop.Word.Application(); object oTemplate = nombreTemplate; _Document oWordDoc = oWordApp.Documents.Add( ref oTemplate, ref oMissing, ref oMissing, ref oMissing); oWordApp.Visible = true; if (oWordDoc.Bookmarks.Exists("NombreDeudor")) { // Setea el valor del Bookmark object oBookMark = "NombreDeudor"; string texto = String.Format("{0}", _control.getNombrePersona()); oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } if (oWordDoc.Bookmarks.Exists("DireccionDeudor")) { // Setea el valor del Bookmark object oBookMark = "DireccionDeudor"; string texto = String.Format("{0}", _control.getDireccionDeudor()); oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } if (oWordDoc.Bookmarks.Exists("CpDeudor")) { // Setea el valor del Bookmark object oBookMark = "CpDeudor"; string texto = String.Format("{0}", _control.getCpDeudor()); oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } if (oWordDoc.Bookmarks.Exists("LocalidadProvincia")) { // Setea el valor del Bookmark object oBookMark = "LocalidadProvincia"; string texto = String.Format("{0}", _control.getLocalidadDeudor()); oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } if (oWordDoc.Bookmarks.Exists("NombreCliente")) { // Setea el valor del Bookmark object oBookMark = "NombreCliente"; string texto = String.Format("{0}", _control.getNombreCliente()); oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } if (oWordDoc.Bookmarks.Exists("CodigoCuenta")) { // Setea el valor del Bookmark object oBookMark = "CodigoCuenta"; string texto = String.Format("{0}", _control.getCodigoCuenta()); oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } }
private void EditMenuItem_Click(object sender, EventArgs e) { var selectNode = radTreeView1.SelectedNode; if (selectNode != null) { try { Word.Application word = new Word.Application(); word.Visible = true; word.Documents.Open(path + "\\RusLanguage\\" + selectNode.Text + ".html"); //word.Documents.OpenNoRepairDialog(path + "\\GeogebraFiles\\" + selectNode.Text + ".html"); } catch (Exception) { MessageBox.Show("Ошибка редактирования", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } } else { MessageBox.Show("Не выбран не один узел для редактирования", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } }
private void viewPlanBTN_Click(object sender, EventArgs e) { var dialogResult = MessageBox.Show(@"Вы действительно хотите просмотреть план за " + monthTB.Text.ToLower() + @" " + yearTB.Text + @" года?", @"Просмотр плана", MessageBoxButtons.YesNo); if (dialogResult != DialogResult.Yes) { return; } string path = Environment.CurrentDirectory + "\\Планы\\" + monthTB.Text.ToLower() + "_" + yearTB.Text + ".docx"; FileInfo fileInf = new FileInfo(path); if (!fileInf.Exists) { MessageBox.Show(@"Файл плана не существует!"); return; } _Application application = new Microsoft.Office.Interop.Word.Application(); application.Documents.Open(path); application.Visible = true; }
private void FindAndReplace(Microsoft.Office.Interop.Word.Application doc, object findText, object replaceWithText) { //options object matchCase = false; object matchWholeWord = true; object matchWildCards = false; object matchSoundsLike = false; object matchAllWordForms = false; object forward = true; object format = false; object matchKashida = false; object matchDiacritics = false; object matchAlefHamza = false; object matchControl = false; object read_only = false; object visible = true; object replace = 2; object wrap = 1; //execute find and replace doc.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl); }
void ReadFile(string adresses_path) { Getter_adresses.Clear(); if (adresses_path.Contains(".txt")) { StreamReader sr = new StreamReader(adresses_path, System.Text.Encoding.Default); string allText = sr.ReadToEnd(); string[] MBAddresses = allText.Split(new char[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); foreach (string li in MBAddresses) { Getter_adresses.Add(li); } sr.Close(); } if (adresses_path.Contains(".doc") || adresses_path.Contains(".docx")) { try { Microsoft.Office.Interop.Word.Application word_app = null; word_app = new Microsoft.Office.Interop.Word.Application(); word_app.Visible = false; Document word_doc = word_app.Documents.Open(adresses_path); Thread t = new Thread(new ThreadStart(() => { for (int i = 0; i < word_doc.Paragraphs.Count; i++) { string[] temp = word_doc.Paragraphs[i + 1].Range.Text.Split(new char[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in temp) { if (item.Contains("@")) { Getter_adresses.Add(item); } } } word_doc.Close(); word_app.Quit(); })); t.IsBackground = false; t.Start(); t.Join(); } catch (Exception e) { MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (adresses_path.Contains(".xls") || adresses_path.Contains(".xlsx")) { try { Stats.count = 0; Microsoft.Office.Interop.Excel._Application excel_app = null; excel_app = new Microsoft.Office.Interop.Excel.Application(); excel_app.Visible = false; _Workbook excel_workbook = excel_app.Workbooks.Open(adresses_path); _Worksheet excel_worksheet = excel_workbook.Sheets[1]; excel_worksheet = excel_workbook.ActiveSheet; Microsoft.Office.Interop.Excel.Range excel_range = excel_worksheet.UsedRange; ScanExcl se = new ScanExcl(excel_app, excel_workbook, excel_worksheet, excel_range); se.ShowDialog(); Getter_adresses = MessageWithData.Getter_Addresses; excel_app.Quit(); try { foreach (Process proc in Process.GetProcessesByName("EXCEL")) { proc.Kill(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } GC.Collect(); } catch (Exception e) { MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (adresses_path.Contains(".accdb") || adresses_path.Contains(".mdb")) { string connection = $"Provider = Microsoft.Jet.OLEDB.4.0; Data Source ={adresses_path};"; //string connection = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={adresses_path};"; OleDbConnection myConnection = new OleDbConnection(connection); myConnection.Open(); OleDbCommand coommand = new OleDbCommand("SELECT Emails_Col FROM Emails", myConnection); OleDbDataReader reader = coommand.ExecuteReader(); Getter_adresses.Clear(); while (reader.Read()) { int AddressIndex = reader.GetOrdinal("Emails_Col"); Getter_adresses.Add(reader.GetString(AddressIndex)); } myConnection.Close(); } }
public void saveDoc(string FileName) { var winword = new Microsoft.Office.Interop.Word.Application(); try { object missing = System.Reflection.Missing.Value; //создаем документ Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing); document.Sections.PageSetup.LeftMargin = 45; //получаем ссылку на параграф var paragraph = document.Paragraphs.Add(missing); var range = paragraph.Range; string title = "Список выполненных заявок за период с " + dateTimePickerFrom.Text + " по " + dateTimePickerTo.Text; //задаем текст range.Text = title; //задаем настройки шрифта var font = range.Font; font.Size = 14; font.Name = "Times New Roman"; font.Bold = 1; //задаем настройки абзаца var paragraphFormat = range.ParagraphFormat; paragraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; paragraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; paragraphFormat.SpaceAfter = 10; paragraphFormat.SpaceBefore = 0; //добавляем абзац в документ range.InsertParagraphAfter(); //создаем таблицу var paragraphTable = document.Paragraphs.Add(Type.Missing); var rangeTable = paragraphTable.Range; var table = document.Tables.Add(rangeTable, dataGridViewReport.Rows.Count + 2, 6, ref missing, ref missing); font = table.Range.Font; font.Size = 14; font.Name = "Times New Roman"; var paragraphTableFormat = table.Range.ParagraphFormat; paragraphTableFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; paragraphTableFormat.SpaceAfter = 0; paragraphTableFormat.SpaceBefore = 0; for (int j = 0; j < dataGridViewReport.Columns.Count - 1; ++j) { table.Cell(1, 1 + j).Range.Text = dataGridViewReport.Columns[j + 1].HeaderCell.Value.ToString(); } for (int i = 0; i < dataGridViewReport.Rows.Count; ++i) { for (int j = 0; j < dataGridViewReport.Columns.Count - 1; ++j) { table.Cell(2 + i, 1 + j).Range.Text = dataGridViewReport.Rows[i].Cells[j + 1].FormattedValue.ToString(); } } List <string> words = new List <string>(); string[] sum = { "", "", "", "", "Итого:" }; words.AddRange(sum); words.Add(textBoxItog.Text); for (int j = 0; j < words.Count; j++) { table.Cell(dataGridViewReport.Rows.Count + 2, 1 + j).Range.Text = words[j]; } table.Cell(dataGridViewReport.Rows.Count + 2, 5).Range.Bold = 1; //задаем границы таблицы table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleInset; table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; //сохраняем object fileFormat = WdSaveFormat.wdFormatXMLDocument; document.SaveAs(FileName, ref fileFormat, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); document.Close(ref missing, ref missing, ref missing); } catch (Exception) { throw; } finally { winword.Quit(); } }
public void GetDocumentsSign(string username, string email, string password, string position, double timer1, double timer2, double timer3) { string[] files = Directory.GetFiles(this.path); object oEndOfDoc = "\\endofdoc"; object oMissing = System.Reflection.Missing.Value; int counter = 0; Microsoft.Office.Interop.Word._Application oWord; Microsoft.Office.Interop.Word._Document oDoc; oWord = new Microsoft.Office.Interop.Word.Application(); oWord.Visible = true; oWord.WindowState = WdWindowState.wdWindowStateMaximize; IntPtr wordHandle = FindWindow(FileExplorer.wordClassName, oWord.Application.Caption); if (wordHandle == IntPtr.Zero) { MessageBox.Show("Word is not running!"); CloseApplication(oWord); return; } foreach (var file in files) { oDoc = oWord.Documents.Open(file, ReadOnly: false); oDoc.ActiveWindow.WindowState = WdWindowState.wdWindowStateMaximize; oDoc.Final = false; if (wordHandle == IntPtr.Zero) { MessageBox.Show("Word is not running!"); CloseApplication(oWord); return; } else { SetForegroundWindow(wordHandle); } object paramNextPage = Microsoft.Office.Interop.Word.WdBreakType.wdLineBreak; oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertBreak(ref paramNextPage); object breakPage = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak; object saveOption = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; object originalFormat = Microsoft.Office.Interop.Word.WdOriginalFormat.wdOriginalDocumentFormat; object routeDocument = false; object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToLine; object which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToLast; object count = 4; Paragraph para = oDoc.Paragraphs.Add(ref oMissing); para.Range.Text = "С уважение!"; para.Range.Font.Size = 12; para.Range.Font.Name = "Times New Roman"; para.Range.InsertParagraphAfter(); oWord.Selection.GoTo(ref what, ref which, ref count, ref oMissing); // oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertBreak(ref paramNextPage); // oWord.Selection.GoTo(ref what, ref which, ref count, ref oMissing); object sigID = "{00000000-0000-0000-0000-000000000000}"; Timer timer = new Timer(); timer.Elapsed += (s, args) => { SendKeys.SendWait("{TAB}"); SendKeys.SendWait("{ENTER}"); timer.Stop(); }; timer.Interval = timer1; timer.Start(); try { oWord.Activate(); Microsoft.Office.Core.SignatureSet signatureSet = oWord.ActiveDocument.Signatures; signatureSet.ShowSignaturesPane = false; Signature objSignature = signatureSet.AddSignatureLine(sigID); objSignature.Setup.SuggestedSigner = username; objSignature.Setup.SuggestedSignerLine2 = position; objSignature.Setup.SuggestedSignerEmail = email; objSignature.Setup.ShowSignDate = true; oWord.Documents.Save(); Timer t1 = new Timer(); Timer t2 = new Timer(); if (counter == 0) { t1.Elapsed += (st, args) => { oWord.Activate(); SendKeys.SendWait(" "); SendKeys.SendWait("{ENTER}"); t2.Start(); t1.Stop(); }; t2.Elapsed += (st1, args1) => { oWord.Activate(); int i = 0; while (i < password.Length) { oWord.Activate(); SendKeys.SendWait(password[i].ToString()); i++; } SendKeys.SendWait("~"); t2.Stop(); }; t1.Interval = timer2; t2.Interval = t1.Interval + timer3; t1.Start(); } else { t1.Elapsed += (st, args) => { oWord.Activate(); SendKeys.SendWait(" "); SendKeys.SendWait("{ENTER}"); t1.Stop(); }; t1.Interval = timer2; t1.Start(); } try { objSignature.Sign(); } catch (Exception ex) { MessageBox.Show($"Документ №{counter} не бе разписан!\n " + ex.ToString()); oDoc.Close(); oWord.Quit(); if (oDoc != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc); } if (oWord != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord); } MessageBox.Show($"Фатална грешка при обработка на документ №{counter}\n" + ex.ToString()); // GC.Collect(); return; } } catch (Exception ex) { CloseDocument(oDoc); CloseApplication(oWord); MessageBox.Show($"Фатална грешка при обработка на документ №{counter}\n" + ex.ToString()); return; } oDoc.Close(); if (oDoc != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc); } counter++; oDoc = null; // GC.Collect(); } CloseApplication(oWord); if (counter > 0) { string msg = String.Format("Всички {0} документа бяха успешно подписани!\n", counter); MessageBox.Show(msg); } }
public _ExcelToWord() { excelApp = new Excel.Application(); wordApp = new Word.Application(); }
public Attachment_6() { excelApp = new Excel.Application(); wordApp = new Word.Application(); }
public BianziADD() { excelApp = new Excel.Application(); wordApp = new Word.Application(); }
/// <summary> /// Este evento responde al boton de Aceptar la generacion de documentos. /// </summary> /// <param name="sender"> /// El objeto que genera el evento. /// </param> /// <param name="e"> /// Los datos asociados al evento. /// </param> private void btnAceptar_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; Sistema.Controlador.Winppal.setAyuda(Mensaje.TextoMensaje("GENERACION-DOC-AYUDA")); try { int creados, errores, bloqueadas; Sistema.Controlador.logear("GENERACION-DOCUMENTOS-INI", ENivelMensaje.INFORMACION, _lista + "/" + txtDescTemplate.Text); int ctdad = creados = errores = bloqueadas = 0; if (ParentForm != null) ParentForm.DialogResult = DialogResult.OK; object oMissing = Missing.Value; String nombreTemplate = String.Format("{0}\\Templates\\{1}", Application.StartupPath, txtDescTemplate.Text); // Abre el Word _Application oWordApp = new Microsoft.Office.Interop.Word.Application(); oWordApp.Visible = false; object oTemplate = nombreTemplate; foreach (Gestion gestion in _lista.ListaGestiones) { _Document oWordDoc = oWordApp.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing); try { ctdad++; // verifica que la gestion recien este creada y no haya sido tocada // o, solo si esta asignada, sea a este usuario o por tener gestor if (gestion.isAlive() && (gestion.Estado.Equals(_creada) || (gestion.Estado.Equals(_asignada) && (gestion.Usuario.Equals(Sistema.Controlador.SecurityService.getUsuario()) || gestion.Cuenta.Gestor != null)))) { // si no fue tocada sigue y crea el documento Cuenta cta = gestion.Cuenta; Persona tit = cta.Titular; Contacto con = tit.getContactoPrincipal(); if (oWordDoc.Bookmarks.Exists("NombreDeudor")) { // Setea el valor del Bookmark object oBookMark = "NombreDeudor"; string texto = String.Format("{0}", tit.Nombre); oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } if (oWordDoc.Bookmarks.Exists("DireccionDeudor")) { // Setea el valor del Bookmark object oBookMark = "DireccionDeudor"; string texto = (con != null) ? String.Format("{0} {1} {2}", (con.Calle ?? "[Sin Dato Calle]"), (con.Puerta ?? string.Empty), (con.PisoDepto ?? string.Empty)) : "[Sin Dato Calle]"; oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } if (oWordDoc.Bookmarks.Exists("CpDeudor")) { // Setea el valor del Bookmark object oBookMark = "CpDeudor"; string texto = (con != null) ? String.Format("{0}", (con.Cp ?? "[Sin Dato CP]")) : "[Sin Dato CP]"; oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } if (oWordDoc.Bookmarks.Exists("LocalidadProvincia")) { // Setea el valor del Bookmark object oBookMark = "LocalidadProvincia"; string texto = (con != null) ? String.Format("{0}, {1}", con.Localidad, con.Provincia) : "[Sin Dato Loc/Prov]"; oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } if (oWordDoc.Bookmarks.Exists("NombreCliente")) { // Setea el valor del Bookmark object oBookMark = "NombreCliente"; string texto = String.Format("{0}", cta.Entidad.Nombre); oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } if (oWordDoc.Bookmarks.Exists("CodigoCuenta")) { // Setea el valor del Bookmark object oBookMark = "CodigoCuenta"; string texto = String.Format("{0}", cta.Codigo); oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = texto; } // graba el documebnto recien creado string nombredoc = txtDestino.Text + "\\Doc_" + _lista.Nombre + "_" + cta.Codigo; oWordDoc.SaveAs(nombredoc); oWordDoc.Close(); // actualiza la gestion para mostrarla en proceso DateTime fecha = DateTime.Now; string descripcion = "DOCUMENTO GENERADO:" + nombredoc.ToUpper() + ".DOC"; Parametro tipo = (_lista.TipoLista.TipoGestion == _postal) ? _respostal : _resterreno; saveResultado(gestion, tipo, descripcion, fecha, tit, con); creados++; } else { bloqueadas++; } } catch (Exception ex) { errores++; oWordDoc.Close(WdSaveOptions.wdDoNotSaveChanges); Sistema.Controlador.mostrar("ACTION-COMPLETE-NOK", ENivelMensaje.ERROR, ex.ToString(), true); } } // close the application oWordApp.Application.Quit(ref oMissing, ref oMissing, ref oMissing); string resultado = string.Format("Procesados: {0}. Completados: {1}. Bloqueados: {2}. Errores: {3}.", ctdad, creados, bloqueadas, errores); Sistema.Controlador.mostrar("GENERACION-DOCUMENTOS-FIN", ENivelMensaje.INFORMACION, resultado, true); } catch (Exception ex) { Sistema.Controlador.mostrar("ACTION-COMPLETE-NOK", ENivelMensaje.ERROR, ex.ToString(), true); } finally { Cursor = Cursors.Default; Sistema.Controlador.Winppal.setAyuda(Mensaje.TextoMensaje("AYUDA-LISTO")); } }
public GangweiForm() { excelApp = new Excel.Application(); wordApp = new Word.Application(); }