public void CopyTable() { templateTable = Document.Tables[1]; range = templateTable.Range; range.SetRange(templateTable.Range.Start, templateTable.Range.End); range.Copy(); }
public static void добавитьФайлToolStripMenuItem_Click(System.Windows.Forms.TextBox textBox, System.Windows.Forms.ComboBox comboBox, System.Windows.Forms.OpenFileDialog openFileDialog1) { if (openFileDialog1.ShowDialog() == DialogResult.OK) //Открытие диалогового окна для открытия файла { S_namefiledirect = openFileDialog1.FileName; //Сохранение в переменную пути к выбранному фалу S_namefile = openFileDialog1.SafeFileName; //Сохранение в переменную имени выбранного файла S_wordapp = new Word.Application(); //Создаем объект Word - равносильно запуску Word. S_wordapp.Visible = false; Object filename = S_namefiledirect; S_worddocument = S_wordapp.Documents.Open(ref filename); //Открываем конкретный существующий word документ из нужной директории. Object begin = Type.Missing; //В документе определяем диапазон,вызовом метода Range Object end = Type.Missing; //с передачей ему начального Word.Range wordrange = S_worddocument.Range(ref begin, ref end); //и конечного значений позиций символов. wordrange.Copy(); //Копирование в буфер обмена. S_text = Clipboard.GetText(); //Сохранение в переменную скопированного текста textBox.Text = S_text; //Извлекаем из буфера обмена копированный текст. comboBox.Items.Add(S_namefile); //Добавление в combobox1 имени файла, с которого мы скопировали текст comboBox.Text = S_namefile; //Надпись комбобокса меняется на имя файла S_nameFile.Add(S_namefile); //Добавление в список имени файла S_textFile.Add(S_text); //Добавление в список текста файла Object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges; Object originalFormat = Word.WdOriginalFormat.wdWordDocument; Object routeDocument = Type.Missing; S_wordapp.Quit(ref saveChanges, ref originalFormat, ref routeDocument); // Закрытие файла S_wordapp = null; } }
public static void copyCellsToTable(Word.Table Realdoc_tbl, Word.Table ListOfEff_tbl, int pageToDo, int FirstHeaderPage) { int leftTbl = pageToDo / 2; int z = 0; int right = pageToDo + FirstHeaderPage; if (pageToDo % 2 != 0) { leftTbl = leftTbl + 1; z = 1; } //left side Word.Range RangeToCopy = ListOfEff_tbl.Range; RangeToCopy.SetRange(ListOfEff_tbl.Rows[FirstHeaderPage + 1].Range.Start, ListOfEff_tbl.Rows[leftTbl + FirstHeaderPage].Range.End); RangeToCopy.Copy(); Word.Range RangeToPaste = Realdoc_tbl.Range; RangeToPaste.SetRange(Realdoc_tbl.Cell(3, 1).Range.Start, Realdoc_tbl.Cell(Realdoc_tbl.Rows.Count, 4).Range.End); RangeToPaste.Select(); RangeToPaste.PasteSpecial(Word.WdPasteDataType.wdPasteRTF); RangeToPaste.Paragraphs.SpaceAfter = 0; RangeToPaste.Paragraphs.SpaceBefore = 0; RangeToPaste.Paragraphs.LeftIndent = 0; RangeToPaste.Paragraphs.RightIndent = 0; RangeToPaste.Paragraphs.KeepWithNext = 0; RangeToPaste.Paragraphs.KeepTogether = 0; RangeToCopy.SetRange(ListOfEff_tbl.Rows[leftTbl + 1 + FirstHeaderPage].Range.Start, ListOfEff_tbl.Rows[right].Range.End); RangeToCopy.Copy(); RangeToPaste.SetRange(Realdoc_tbl.Cell(3, 5).Range.Start, Realdoc_tbl.Cell(Realdoc_tbl.Rows.Count - z, 8).Range.End); RangeToPaste.Select(); RangeToPaste.PasteSpecial(Word.WdPasteDataType.wdPasteRTF); RangeToPaste.Paragraphs.SpaceAfter = 0; RangeToPaste.Paragraphs.SpaceBefore = 0; RangeToPaste.Paragraphs.LeftIndent = 0; RangeToPaste.Paragraphs.KeepWithNext = 0; RangeToPaste.Paragraphs.KeepTogether = 0; RangeToPaste.Paragraphs.RightIndent = 0; Realdoc_tbl.Cell(1, 1).Range.ListFormat.RemoveNumbers(); }
private List <string> G_Str_Files = new List <string>(); //定义字符串集合 private void btn_split_Click(object sender, EventArgs e) { btn_Merge.Enabled = false; //停用合并按钮 ThreadPool.QueueUserWorkItem( //开始线程池 (pp) => //使用lambda表达式 { G_wa = new Microsoft.Office.Interop.Word.Application(); //创建应用程序对象 Word.Document P_MainDocument = //新建合并文档对象 G_wa.Documents.Add(ref G_missing, ref G_missing , ref G_missing, ref G_missing); foreach (string P_Str in G_Str_Files) //遍历文档的集合 { object P_strs = P_Str; //创建object对象 Word.Document P_Document = G_wa.Documents.Open( //打开Word文档 ref P_strs, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref o); Word.Range P_Range_temp = //得到文档全部范围 P_Document.Range(ref G_missing, ref G_missing); P_Range_temp.Select(); //选择文档全部范围 P_Range_temp.Copy(); //复制文档全部范围 Word.Range P_Range_temp2 = //得到文档的范围 P_MainDocument.Range(ref G_missing, ref G_missing); object P_end = Word.WdCollapseDirection.wdCollapseEnd; //创建object对象 P_Range_temp2.Collapse(ref P_end); //折叠文档范围 P_Range_temp2.Select(); //选择档的最后位置 P_Range_temp2.Paste(); //粘贴文档内容 ((Word._Document)P_Document).Close(ref G_missing, ref G_missing, //关闭文档 ref G_missing); } object P_SavePath = G_SaveFileDialog.FileName; //创建object对象 P_MainDocument.SaveAs( //保存合并后的文档 ref P_SavePath, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing); ((Word._Application)G_wa.Application).Quit( //退出应用程序 ref G_missing, ref G_missing, ref G_missing); this.Invoke( //调用窗体线程 (MethodInvoker)(() => //使用lambda表达式 { Clipboard.Clear(); //清空剪切板 MessageBox.Show( //提示已经创建Word "成功合并Word文档!", "提示!"); btn_Merge.Enabled = true; //启用合并按钮 })); }); }
private List <string> G_Str_Files = new List <string>(); //定義字串集合 private void btn_split_Click(object sender, EventArgs e) { btn_Merge.Enabled = false; //停用合併按鈕 ThreadPool.QueueUserWorkItem( //開始線程池 (pp) => //使用lambda表達式 { G_wa = new Microsoft.Office.Interop.Word.Application(); //建立應用程式物件 Word.Document P_MainDocument = //新建合併文件檔物件 G_wa.Documents.Add(ref G_missing, ref G_missing , ref G_missing, ref G_missing); foreach (string P_Str in G_Str_Files) //深度搜尋文件檔的集合 { object P_strs = P_Str; //建立object物件 Word.Document P_Document = G_wa.Documents.Open( //打開Word文件檔 ref P_strs, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref G_missing); Word.Range P_Range_temp = //得到文件檔全部範圍 P_Document.Range(ref G_missing, ref G_missing); P_Range_temp.Select(); //選擇文件檔全部範圍 P_Range_temp.Copy(); //複製文件檔全部範圍 Word.Range P_Range_temp2 = //得到文件檔的範圍 P_MainDocument.Range(ref G_missing, ref G_missing); object P_end = Word.WdCollapseDirection.wdCollapseEnd; //建立object物件 P_Range_temp2.Collapse(ref P_end); //折疊文件檔範圍 P_Range_temp2.Select(); //選擇檔的最後位置 P_Range_temp2.Paste(); //貼上文件檔內容 ((Word._Document)P_Document).Close(ref G_missing, ref G_missing, //關閉文件檔 ref G_missing); } object P_SavePath = G_SaveFileDialog.FileName; //建立object物件 P_MainDocument.SaveAs( //儲存合併後的文件檔 ref P_SavePath, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing); ((Word._Application)G_wa.Application).Quit( //退出應用程式 ref G_missing, ref G_missing, ref G_missing); this.Invoke( //呼叫視窗線程 (MethodInvoker)(() => //使用lambda表達式 { Clipboard.Clear(); //清空剪下板 MessageBox.Show( //提示已經建立Word "成功合併Word文件檔!", "提示!"); btn_Merge.Enabled = true; //啟用合併按鈕 })); }); }
/// <summary> /// !!! 正式开始提取数据 /// </summary> /// <param name="DataTableInWord">进行数据提取的word中的表格Table对象</param> /// <remarks>提取的基本思路:已有一个doc对象,并对其中的一个测点进行提取。</remarks> private void ExportData(Microsoft.Office.Interop.Word.Table DataTableInWord) { try { Microsoft.Office.Interop.Word.Range rgTable = DataTableInWord.Range; rgTable.Copy(); this.F_BufferSheet.UsedRange.Clear(); this.F_BufferSheet.Activate(); this.F_BufferSheet.UsedRange.Clear(); this.F_BufferSheet.Cells[1, 1].select(); this.F_BufferSheet.Paste(); //此文档中的每一个要提取的测点。 foreach (Microsoft.Office.Interop.Excel.Worksheet sheetExportTo in this.F_DicPointsInfo.Keys) { PointsInfoForExport PointInfo = this.F_DicPointsInfo.Item(sheetExportTo); // ------------ 从暂存工作表中将测点标签与对应的数据提取到目标工作表中 ---------- //搜索得到的第一个结果的range对象,如果没有搜索到,则返回nothing。 Microsoft.Office.Interop.Excel.Range rgNextPoint = default(Microsoft.Office.Interop.Excel.Range); rgNextPoint = this.F_BufferSheet.UsedRange.Find(What: ref PointInfo.PointTag, SearchOrder: ref PointInfo.SearchOrder, LookAt: ref XlLookAt.xlPart, LookIn: ref XlFindLookIn.xlValues, SearchDirection: ref XlSearchDirection.xlNext, MatchCase: false); if (rgNextPoint != null) { //当搜索到指定查找区域的末尾时,此方法将绕回到区域的开始位置继续搜索。 //发生绕回后,要停止搜索,可保存第一个找到的单元格地址,然后测试后面找到的每个单元格地址是否与其相同。 string firstAddress = rgNextPoint.Address; //提取数据并写入最终的工作表 do { sheetExportTo.Cells[PointInfo.RowNumToBeWritten, PointInfo.ColNumToBeWritten].Value = rgNextPoint.Value; sheetExportTo.Cells[PointInfo.RowNumToBeWritten, PointInfo.ColNumToBeWritten + 1].Value = rgNextPoint PointInfo.Offset[0, PointInfo.Offset].Value; PointInfo.RowNumToBeWritten++; rgNextPoint = this.F_BufferSheet.UsedRange.FindNext(rgNextPoint); } while (rgNextPoint != null && string.Compare(rgNextPoint.Address, firstAddress) != 0); } } } catch (Exception) { //数据提取出错 string strError = ""; this.F_ErrorList.Add(strError); } finally { } }
private void CreateNewGuidanceDocument(IList <string> addedDocs, Word.Range range, string pageFullFilePath) { var document = range.Application.ActiveDocument; var pageFileName = Path.GetFileNameWithoutExtension(pageFullFilePath); var targetPath = Path.GetDirectoryName(pageFullFilePath); var savedFilename = Path.ChangeExtension(pageFileName, ContentFileExtension); // Create new document tracer.Info( Resources.TocGuidanceProcessor_TraceTopicCreated, pageFileName); try { // Copy existing content range.Copy(); PasteNewDocument(targetPath, pageFileName, pageFullFilePath, document); if (addedDocs.Contains(savedFilename)) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.TocGuidanceProcessor_ErrorDuplicateTopic, pageFileName)); } else { addedDocs.Add(savedFilename); } } finally { try { // Clear clipboard Clipboard.Clear(); } catch (ThreadStateException) { } } }
private FolderBrowserDialog G_FolderBrowserDailog; //定义浏览文件夹对话框字段 private void btn_Get_Click(object sender, EventArgs e) { btn_split.Enabled = false; //停用分割按钮 ThreadPool.QueueUserWorkItem( //开始线程池 (pp) => //使用lambda表达式 { G_wa = new Microsoft.Office.Interop.Word.Application(); //创建应用程序对象 object P_OpenFileDialog = //创建object对象 G_OpenFileDialog.FileName; Word.Document P_Document = G_wa.Documents.Open( //打开Word文档 ref P_OpenFileDialog, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref G_missing); bool P_bl = false; this.Invoke( //调用窗体线程 (MethodInvoker)(() => //使用lambda表达式 { P_bl = cbox_Select.SelectedIndex == 0; })); if (P_bl) //判断使用什么方式分割文档 { foreach (Word.Paragraph Paragraph in G_wa.ActiveDocument.Paragraphs) { Paragraph.Range.Select(); //选择段落 Paragraph.Range.Copy(); //将段落放入剪切板 AddFile(); //将剪切板内的数据放入新建文件 } } else { Word.Range P_Range = G_wa.ActiveDocument.Content; //得到文档区域 int P_int_count = P_Range.Text.Length; //得到文档字符总长度 int P_int_i = P_int_count / 100; //计算循环建立文档次数 if (P_int_i > 0) //如果文档内文字大于100个 { for (int i = 0; i < P_int_i; i++) //开始循环创建文档 { object P_o1 = i == 0 ? 0 : i * 100 + 1; //复制文档范围的开始部份 object P_o2 = i * 100 + 101; //复制文档范围的结尾部份 Word.Range P_Range_temp = //得到文档的范围 G_wa.ActiveDocument.Range(ref P_o1, ref P_o2); P_Range.Select(); //选中文档范围 P_Range_temp.Copy(); //将选择文档范围放入剪切板 AddFile(); //将剪切板内的数据放入新建文件 } object P_o11 = P_int_i * 100 + 1; //复制文档范围的开始部份 Word.Range P_Range_temp1 = //得到文档的范围 G_wa.ActiveDocument.Range(ref P_o11, ref G_missing); P_Range.Select(); //选中文档范围 P_Range_temp1.Copy(); //将选择文档范围放入剪切板 AddFile(); //将剪切板内的数据放入新建文件 } else { Word.Range P_Range2 = //得到文档区域 G_wa.ActiveDocument.Content; P_Range.Select(); //选中文档范围 P_Range2.Copy(); //将选择文档范围放入剪切板 AddFile(); //将剪切板内的数据放入新建文件 } } ((Word._Application)G_wa.Application).Quit( //退出应用程序 ref G_missing, ref G_missing, ref G_missing); this.Invoke( //调用窗体线程 (MethodInvoker)(() => //使用lambda表达式 { Clipboard.Clear(); //清空剪切板 MessageBox.Show( //提示已经创建Word "分割文档完成!", "提示!"); btn_split.Enabled = true; //启用分割按钮 })); }); }
public void ImprimirEtiquetasArreglos(JObject pJDocumento, int pIdImpresionTemplate, string pRutaTemplate, CConexion pConexion) { CImpresionEtiquetas ImpresionEtiquetas = new CImpresionEtiquetas(); Dictionary <string, object> Parametros = new Dictionary <string, object>(); Parametros.Add("IdImpresionTemplate", pIdImpresionTemplate); object oEndOfDoc = "\\endofdoc"; /* \endofdoc es un bookmark predefinido */ Object oMissing = System.Reflection.Missing.Value; Word.Range wrdRng = documentoWord.Bookmarks.get_Item(ref oEndOfDoc).Range; int ind = 0; object oPos; double dPos = aplicacionWord.InchesToPoints(10); foreach (JProperty oPropiedadDocumento in pJDocumento.Properties()) { if (oPropiedadDocumento.Value.Type.ToString() == "Object") { JObject JTablaConceptos = new JObject(); JTablaConceptos = (JObject)pJDocumento[oPropiedadDocumento.Name]; foreach (JProperty oPropiedadTabla in JTablaConceptos.Properties()) { if (oPropiedadTabla.Name == "Tipo") { if (oPropiedadTabla.Value.ToString() == "Conceptos") { for (int i = 1; i <= documentoWord.Tables.Count; i++) { Word.Table wTable = documentoWord.Tables[i]; Word.Cell pCell = wTable.Cell(1, 1); if (wTable.ID != null && wTable.ID == "tblReceptor") { foreach (CImpresionEtiquetas oImpresionEtiqueta in ImpresionEtiquetas.LlenaObjetosFiltros(Parametros, pConexion)) { Word.Range rangePlantilla = wTable.Range; int rc = wTable.Rows.Count; // Selecciona y copia el renglon Layout. rangePlantilla.Start = 1; rangePlantilla.End = wTable.Rows[rc].Cells[wTable.Rows[rc].Cells.Count].Range.End; rangePlantilla.Find.ClearFormatting(); rangePlantilla.Find.Text = oImpresionEtiqueta.Etiqueta; rangePlantilla.Find.Replacement.ClearFormatting(); if (pJDocumento[oImpresionEtiqueta.Campo] != null) { rangePlantilla.Find.Replacement.Text = pJDocumento[oImpresionEtiqueta.Campo].ToString(); } object replaceAll = Word.WdReplace.wdReplaceAll; rangePlantilla.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } } if (wTable.ID != null && wTable.ID == JTablaConceptos["NombreTabla"].ToString()) { bool pRowsNum = false; if (wTable.Rows.Count > 1) { pRowsNum = true; } int contador = 1; // Layaout foreach (JObject JInventario in JTablaConceptos["Inventarios"]) { contador = contador + 1; Word.Range range = wTable.Range; // Renglon Layout int selectedRow = 1; // Selecciona y copia el renglon Layout. range.Start = wTable.Rows[selectedRow].Cells[1].Range.Start; range.End = wTable.Rows[selectedRow].Cells[wTable.Rows[selectedRow].Cells.Count].Range.End; range.Copy(); // Inserta renglon nuevo al final de la tabla. wTable.Rows.Add(ref oMissing); // Mueve el cursor a la primera celda del renglon nuevo. range.Start = wTable.Rows[wTable.Rows.Count].Cells[1].Range.Start; range.End = range.Start; // Pega los valores del renglon layout al renglon nuevo. range.Paste(); int m = wTable.Rows.Count; Word.Row renglonPlantilla = wTable.Rows[m]; Word.Cell celdaPlantilla = renglonPlantilla.Cells[1]; for (int x = 1; x <= celdaPlantilla.Tables.Count; x++) { bool sRowsNum = false; if (celdaPlantilla.Tables[x].Rows.Count > 3) { sRowsNum = true; } foreach (CImpresionEtiquetas oImpresionEtiqueta in ImpresionEtiquetas.LlenaObjetosFiltros(Parametros, pConexion)) { Word.Range rangePlantilla = wTable.Range; // Selecciona y copia el renglon Layout. rangePlantilla.Start = celdaPlantilla.Tables[x].Rows[1].Cells[1].Range.Start; rangePlantilla.End = celdaPlantilla.Tables[x].Rows[1].Cells[celdaPlantilla.Tables[x].Rows[1].Cells.Count].Range.End; rangePlantilla.Find.ClearFormatting(); rangePlantilla.Find.Text = oImpresionEtiqueta.Etiqueta; rangePlantilla.Find.Replacement.ClearFormatting(); if (JInventario[oImpresionEtiqueta.Campo] != null) { rangePlantilla.Find.Replacement.Text = JInventario[oImpresionEtiqueta.Campo].ToString(); } object replaceAll = Word.WdReplace.wdReplaceAll; rangePlantilla.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } foreach (JObject JConcepto in JInventario["Lista"]) { Word.Range sRange = celdaPlantilla.Tables[x].Range; // Selecciona y copia el renglon Layout. sRange.Start = celdaPlantilla.Tables[x].Rows[3].Cells[1].Range.Start; sRange.End = celdaPlantilla.Tables[x].Rows[3].Cells[celdaPlantilla.Tables[x].Rows[3].Cells.Count].Range.End; sRange.Copy(); // Inserta renglon nuevo al final de la tabla. celdaPlantilla.Tables[x].Rows.Add(ref oMissing); // Mueve el cursor a la primera celda del renglon nuevo. sRange.Start = celdaPlantilla.Tables[x].Rows[celdaPlantilla.Tables[x].Rows.Count].Cells[1].Range.Start; sRange.End = sRange.Start; // Pega los valores del renglon layout al renglon nuevo. sRange.Paste(); foreach (CImpresionEtiquetas oImpresionEtiqueta in ImpresionEtiquetas.LlenaObjetosFiltros(Parametros, pConexion)) { Word.Range rowRange = wTable.Range; // Selecciona y copia el renglon Layout. sRange.Find.ClearFormatting(); sRange.Find.Text = oImpresionEtiqueta.Etiqueta; sRange.Find.Replacement.ClearFormatting(); if (JConcepto[oImpresionEtiqueta.Campo] != null) { sRange.Find.Replacement.Text = JConcepto[oImpresionEtiqueta.Campo].ToString(); } object replaceAll = Word.WdReplace.wdReplaceAll; sRange.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } } if (sRowsNum) { JObject JTotal = new JObject(); JTotal = (JObject)JInventario["Total"]; Word.Range sRange = celdaPlantilla.Tables[x].Range; // Selecciona y copia el renglon Layout. sRange.Start = celdaPlantilla.Tables[x].Rows[4].Cells[1].Range.Start; sRange.End = celdaPlantilla.Tables[x].Rows[4].Cells[celdaPlantilla.Tables[x].Rows[4].Cells.Count].Range.End; sRange.Copy(); // Inserta renglon nuevo al final de la tabla. celdaPlantilla.Tables[x].Rows.Add(ref oMissing); // Mueve el cursor a la primera celda del renglon nuevo. sRange.Start = celdaPlantilla.Tables[x].Rows[celdaPlantilla.Tables[x].Rows.Count].Cells[1].Range.Start; sRange.End = sRange.Start; // Pega los valores del renglon layout al renglon nuevo. sRange.Paste(); foreach (CImpresionEtiquetas oImpresionEtiqueta in ImpresionEtiquetas.LlenaObjetosFiltros(Parametros, pConexion)) { Word.Range rowRange = wTable.Range; // Selecciona y copia el renglon Layout. sRange.Find.ClearFormatting(); sRange.Find.Text = oImpresionEtiqueta.Etiqueta; sRange.Find.Replacement.ClearFormatting(); if (JTotal[oImpresionEtiqueta.Campo] != null) { sRange.Find.Replacement.Text = JTotal[oImpresionEtiqueta.Campo].ToString(); } object replaceAll = Word.WdReplace.wdReplaceAll; sRange.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } celdaPlantilla.Tables[x].Rows[4].Delete(); } celdaPlantilla.Tables[x].Rows[3].Delete(); } } if (pRowsNum) { Word.Range sRange = wTable.Range; // Selecciona y copia el renglon Layout. sRange.Start = wTable.Rows[2].Cells[1].Range.Start; sRange.End = wTable.Rows[2].Cells[wTable.Rows[2].Cells.Count].Range.End; sRange.Copy(); // Inserta renglon nuevo al final de la tabla. wTable.Rows.Add(ref oMissing); // Mueve el cursor a la primera celda del renglon nuevo. sRange.Start = wTable.Rows[wTable.Rows.Count].Cells[1].Range.Start; sRange.End = sRange.Start; // Pega los valores del renglon layout al renglon nuevo. sRange.Paste(); foreach (CImpresionEtiquetas oImpresionEtiqueta in ImpresionEtiquetas.LlenaObjetosFiltros(Parametros, pConexion)) { Word.Range rangePlantilla = wTable.Range; // Selecciona y copia el renglon Layout. rangePlantilla.Find.ClearFormatting(); rangePlantilla.Find.Text = oImpresionEtiqueta.Etiqueta; rangePlantilla.Find.Replacement.ClearFormatting(); if (pJDocumento[oImpresionEtiqueta.Campo] != null) { rangePlantilla.Find.Replacement.Text = pJDocumento[oImpresionEtiqueta.Campo].ToString(); } object replaceAll = Word.WdReplace.wdReplaceAll; rangePlantilla.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } wTable.Rows[2].Delete(); } wTable.Rows[1].Delete(); } } } } } } } }
private void toDocButton_Click(object sender, EventArgs e) { string name = nameTextbox.Text; string householdId = householdIdTextbox.Text; string dob = dobDatetimePicker.Value.ToString("ddMMyyyy"); bool gender = maleCheckbox.Checked ? true : false; string id = idTextbox.Text; string address = addressTextbox.Text; string update = updateRichTextbox.Text; string attachment = attachmentRichTextbox.Text; if (genFilePath == null || genFilePath == "") { MessageBox.Show("Chọn file"); return; } if (name == "") { MessageBox.Show("Điền tên"); return; } init(); FindAndReplace(templateDoc, "{name}", name.ToUpper()); char[] dobArr = dob.ToCharArray(); for (int i = 0; i < dobArr.Length; i++) { FindAndReplace(templateDoc, "{d" + i + "}", dobArr[i].ToString()); } string checkLoc = gender ? "0" : "1"; string uncheckLoc = !gender ? "0" : "1"; FindAndReplace(templateDoc, "{s" + checkLoc + "}", "X"); FindAndReplace(templateDoc, "{s" + uncheckLoc + "}", ""); char[] idArr = id.ToCharArray(); for (int i = 0; i < 12; i++) { if (i < idArr.Length) { FindAndReplace(templateDoc, "{i" + i + "}", idArr[i].ToString()); } else { FindAndReplace(templateDoc, "{i" + i + "}", ""); } } FindAndReplace(templateDoc, "{address}", address); FindAndReplace(templateDoc, "{update}", update); FindAndReplace(templateDoc, "{attachment}", attachment); Word.Range source = templateDoc.Content; source.Copy(); generatedDoc.Characters.Last.Select(); wordApplication.Selection.Collapse(); Object objUnit = Word.WdUnits.wdStory; wordApplication.Selection.EndKey(ref objUnit, null); wordApplication.Selection.PasteAndFormat(Word.WdRecoveryType.wdPasteDefault); generatedDoc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak); generatedDoc.Save(); templateDoc.Close(SaveChanges: Word.WdSaveOptions.wdDoNotSaveChanges); nameTextbox.Text = ""; householdIdTextbox.Text = ""; dobDatetimePicker.Value = DateTime.Now; maleCheckbox.Checked = true; idTextbox.Text = ""; updateRichTextbox.Text = ""; attachmentRichTextbox.Text = ""; }
public static bool TableToExcel(Word.Range _ran, string RangeOnly = "table", Excel.Worksheet _sht = null) { Excel.Application _excel = null; Excel.Workbook _book = null; try { if (_sht == null) { _excel = new Excel.Application(); _excel.Visible = true; _book = _excel.Workbooks.Add(); if (_book.Sheets.Count > 0) { _sht = _book.Sheets[_book.Sheets.Count]; } else { _sht = _book.Sheets.Add(Type.Missing, _book.Sheets[_book.Sheets.Count], Type.Missing, Type.Missing); } } /*foreach (Word.Cell _cell in _ran.Cells) * { * * }*/ if (Properties.Settings.Default.XLSNewLine && RangeOnly != "range") { long row_count = _ran.Rows.Count; long col_count = _ran.Columns.Count; long i = 1; //row long j = 1; //col foreach (Word.Cell _cel in _ran.Cells) { String _val = String.Concat(_cel.Range.Text.Substring(0, _cel.Range.Text.Length - 1)); //_val.Replace(Environment.NewLine.ToCharArray()[0], '\v'); string _temp = (char)10 + ""; _val = _val.Replace(Environment.NewLine.ToCharArray()[0].ToString(), _temp); _sht.Cells[i, j] = _val.Substring(0, _val.Length - 1); if (j == col_count) { j = 1; i++; } else { j++; } } } else { _ran.Copy(); _sht.Paste(); } _sht.get_Range("A1", "A1").Select(); } catch { return(false); } finally { if (_book != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(_book); } if (_excel != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(_excel); } GC.Collect(); } return(true); }
private FolderBrowserDialog G_FolderBrowserDailog; //定義瀏覽資料夾對話框欄位 private void btn_Get_Click(object sender, EventArgs e) { btn_split.Enabled = false; //停用分割按鈕 ThreadPool.QueueUserWorkItem( //開始線程池 (pp) => //使用lambda表達式 { G_wa = new Microsoft.Office.Interop.Word.Application(); //建立應用程式物件 object P_OpenFileDialog = //建立object物件 G_OpenFileDialog.FileName; Word.Document P_Document = G_wa.Documents.Open( //打開Word文件檔 ref P_OpenFileDialog, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref G_missing , ref G_missing, ref G_missing, ref G_missing, ref G_missing); bool P_bl = false; this.Invoke( //呼叫視窗線程 (MethodInvoker)(() => //使用lambda表達式 { P_bl = cbox_Select.SelectedIndex == 0; })); if (P_bl) //判斷使用什麼方式分割文件檔 { foreach (Word.Paragraph Paragraph in G_wa.ActiveDocument.Paragraphs) { Paragraph.Range.Select(); //選擇段落 Paragraph.Range.Copy(); //將段落放入剪下板 AddFile(); //將剪下板內的資料放入新建文件 } } else { Word.Range P_Range = G_wa.ActiveDocument.Content; //得到文件檔區域 int P_int_count = P_Range.Text.Length; //得到文件檔字符總長度 int P_int_i = P_int_count / 100; //計算循環建立文件檔次數 if (P_int_i > 0) //如果文件檔內文字大於100個 { for (int i = 0; i < P_int_i; i++) //開始循環建立文件檔 { object P_o1 = i == 0 ? 0 : i * 100 + 1; //複製文件檔範圍的開始部份 object P_o2 = i * 100 + 101; //複製文件檔範圍的結尾部份 Word.Range P_Range_temp = //得到文件檔的範圍 G_wa.ActiveDocument.Range(ref P_o1, ref P_o2); P_Range.Select(); //選中文件檔範圍 P_Range_temp.Copy(); //將選擇文件檔範圍放入剪下板 AddFile(); //將剪下板內的資料放入新建文件 } object P_o11 = P_int_i * 100 + 1; //複製文件檔範圍的開始部份 Word.Range P_Range_temp1 = //得到文件檔的範圍 G_wa.ActiveDocument.Range(ref P_o11, ref G_missing); P_Range.Select(); //選中文件檔範圍 P_Range_temp1.Copy(); //將選擇文件檔範圍放入剪下板 AddFile(); //將剪下板內的資料放入新建文件 } else { Word.Range P_Range2 = //得到文件檔區域 G_wa.ActiveDocument.Content; P_Range.Select(); //選中文件檔範圍 P_Range2.Copy(); //將選擇文件檔範圍放入剪下板 AddFile(); //將剪下板內的資料放入新建文件 } } ((Word._Application)G_wa.Application).Quit( //退出應用程式 ref G_missing, ref G_missing, ref G_missing); this.Invoke( //呼叫視窗線程 (MethodInvoker)(() => //使用lambda表達式 { Clipboard.Clear(); //清空剪下板 MessageBox.Show( //提示已經建立Word "分割文件檔完成!", "提示!"); btn_split.Enabled = true; //啟用分割按鈕 })); }); }
private void ButtonPrintLetter_Click(object sender, RoutedEventArgs e) { try { if (TextBlockDataFilePatch.Text == "") { return; } if (TextBlockTemplateFilePatch.Text == "") { return; } FileInfo fiDataFilePatch = new FileInfo(TextBlockDataFilePatch.Text); FileInfo fiTemplateFilePatch = new FileInfo(TextBlockTemplateFilePatch.Text); // Проверяем, что выбранные файлы существуют if (fiDataFilePatch.Exists && fiTemplateFilePatch.Exists) { // Открываем файл Excel с данными Excel.Application excel = new Excel.Application(); Excel.Workbook wbv = excel.Workbooks.Open(TextBlockDataFilePatch.Text, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); Excel.Worksheet wx = (Excel.Worksheet)wbv.Worksheets.get_Item(1); // word - файл с шаблоном пригласительного письма, // в нем далее будут формироваться (добавляться в конец) // письма по всем компаниям Word._Application word = new Word.Application(); // word2 - файл с шаблоном пригласительного письма, // который используется единожды для заполнения // данных по конкретной компании, после чего // листы добавляются в конец word Word._Application word2 = new Word.Application(); // Открываем файл шаблоном пригласительного письма Word.Document wordFile = word.Documents.Open(TextBlockTemplateFilePatch.Text); // Номер строки, в которой указана первая компания int i = Convert.ToInt32(TextBoxNumberFrom.Text.ToString()); // Заполняются данные по первой компании wordFile.FormFields["ТекстовоеПоле1"].Range.Text = wx.Cells[i, 4].Text; wordFile.FormFields["ТекстовоеПоле2"].Range.Text = wx.Cells[i, 2].Text; wordFile.FormFields["ТекстовоеПоле3"].Range.Text = wx.Cells[i, 8].Text; wordFile.FormFields["ТекстовоеПоле4"].Range.Text = wx.Cells[i, 3].Text; wordFile.FormFields["ТекстовоеПоле5"].Range.Text = wx.Cells[i, 6].Text; wordFile.FormFields["ТекстовоеПоле6"].Range.Text = wx.Cells[i, 7].Text; // В конец файла добавляется новый пустой абзац object oEndofDoc = "\\endofdoc"; object oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; Word.Paragraph par = wordFile.Content.Paragraphs.Add(ref oRng); // В конец файла добавляется разрыв страницы object unit; object extend; unit = Word.WdUnits.wdStory; extend = Word.WdMovementType.wdMove; word.Selection.EndKey(ref unit, ref extend); object oType; oType = Word.WdBreakType.wdSectionBreakNextPage; word.Selection.InsertBreak(ref oType); // После разрыва страницы снова добавляется пустой абзац oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; par = wordFile.Content.Paragraphs.Add(ref oRng); object missing = System.Reflection.Missing.Value; object readOnly = true; // Запоминаем номер строки, до которой необходимо вывести данные int N = Convert.ToInt32(TextBoxNumberBefor.Text.ToString()); for (i++; i <= N; i++) { // Открываем файл с шаблоном пригласительного письма Word._Document oDoc = word2.Documents.Open(TextBlockTemplateFilePatch.Text, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); Word.Range oRange = oDoc.Content; // Заполняются данные по первой компании oDoc.FormFields["ТекстовоеПоле1"].Range.Text = wx.Cells[i, 4].Text; oDoc.FormFields["ТекстовоеПоле2"].Range.Text = wx.Cells[i, 2].Text; oDoc.FormFields["ТекстовоеПоле3"].Range.Text = wx.Cells[i, 8].Text; oDoc.FormFields["ТекстовоеПоле4"].Range.Text = wx.Cells[i, 3].Text; oDoc.FormFields["ТекстовоеПоле5"].Range.Text = wx.Cells[i, 6].Text; oDoc.FormFields["ТекстовоеПоле6"].Range.Text = wx.Cells[i, 7].Text; // Копируем шаблон с заполненными данными в буфер обмена oRange.Copy(); // Вставляем из буфера обмена страницы в конец wordFile par.Range.Paste(); // В конец файла wordFile добавляется разрыв страницы unit = Word.WdUnits.wdStory; extend = Word.WdMovementType.wdMove; word.Selection.EndKey(ref unit, ref extend); oType = Word.WdBreakType.wdSectionBreakNextPage; word.Selection.InsertBreak(ref oType); // В конец файла wordFile добавляется разрыв страницы oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; par = wordFile.Content.Paragraphs.Add(ref oRng); // Закрываем файл oDoc oDoc.Close(false, Type.Missing, Type.Missing); } // Показывваем файл со всеми заполненными пригласительными письмами word.Visible = true; // Сохраняем файл //SaveAsFile(wordFile); //wordFile.Close(); // Закрываем исходный файл Excel с данными wbv.Close(false, Type.Missing, Type.Missing); excel.Quit(); } else { MessageBox.Show("Выберитие файл шаблона и файл с данными"); } } catch (Exception ex) { // Показываем сообщение об ошибке MessageBox.Show(ex.Message); } }
private void ButtonPrintLetterBox_Click(object sender, RoutedEventArgs e) { try { if (TextBlockDataFilePatch.Text == "") { return; } if (TextBlockTemplateLetterPatch.Text == "") { return; } FileInfo fiDataFilePatch = new FileInfo(TextBlockDataFilePatch.Text); FileInfo fiTemplateFilePatch = new FileInfo(TextBlockTemplateLetterPatch.Text); if (fiDataFilePatch.Exists && fiTemplateFilePatch.Exists) { Excel.Application excel = new Excel.Application(); Excel.Workbook wbv = excel.Workbooks.Open(TextBlockDataFilePatch.Text, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); Excel.Worksheet wx = (Excel.Worksheet)wbv.Worksheets.get_Item(1); Word._Application word = new Word.Application(); Word._Application word2 = new Word.Application(); //oDoc.Activate(); Word.Document wordFile = word.Documents.Open(TextBlockTemplateLetterPatch.Text); // word.Documents.Add(); int i = Convert.ToInt32(TextBoxNumberFrom.Text.ToString()); wordFile.FormFields["ТекстовоеПоле1"].Range.Text = wx.Cells[i, 4].Text; wordFile.FormFields["ТекстовоеПоле2"].Range.Text = wx.Cells[i, 2].Text; wordFile.FormFields["ТекстовоеПоле3"].Range.Text = wx.Cells[i, 8].Text; wordFile.FormFields["ТекстовоеПоле4"].Range.Text = wx.Cells[i, 13].Text; wordFile.FormFields["ТекстовоеПоле5"].Range.Text = wx.Cells[i, 12].Text; wordFile.FormFields["ТекстовоеПоле6"].Range.Text = wx.Cells[i, 13].Text; object oEndofDoc = "\\endofdoc"; object oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; Word.Paragraph par = wordFile.Content.Paragraphs.Add(ref oRng); object unit; object extend; unit = Word.WdUnits.wdStory; extend = Word.WdMovementType.wdMove; word.Selection.EndKey(ref unit, ref extend); object oType; oType = Word.WdBreakType.wdSectionBreakNextPage; word.Selection.InsertBreak(ref oType); oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; par = wordFile.Content.Paragraphs.Add(ref oRng); object missing = System.Reflection.Missing.Value; object readOnly = true; //word.Visible = true; int N = Convert.ToInt32(TextBoxNumberBefor.Text.ToString()); for (i++; i <= N; i++) { Word._Document oDoc = word2.Documents.Open(TextBlockTemplateLetterPatch.Text, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); Word.Range oRange = oDoc.Content; oDoc.FormFields["ТекстовоеПоле1"].Range.Text = wx.Cells[i, 4].Text; oDoc.FormFields["ТекстовоеПоле2"].Range.Text = wx.Cells[i, 2].Text; oDoc.FormFields["ТекстовоеПоле3"].Range.Text = wx.Cells[i, 8].Text; oDoc.FormFields["ТекстовоеПоле4"].Range.Text = wx.Cells[i, 13].Text; oDoc.FormFields["ТекстовоеПоле5"].Range.Text = wx.Cells[i, 12].Text; oDoc.FormFields["ТекстовоеПоле6"].Range.Text = wx.Cells[i, 13].Text; oRange.Copy(); par.Range.Paste(); unit = Word.WdUnits.wdStory; extend = Word.WdMovementType.wdMove; word.Selection.EndKey(ref unit, ref extend); oType = Word.WdBreakType.wdSectionBreakNextPage; word.Selection.InsertBreak(ref oType); oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; par = wordFile.Content.Paragraphs.Add(ref oRng); oDoc.Close(false, Type.Missing, Type.Missing); } word.Visible = true; //SaveAsFile(wordFile); //wordFile.Close(); wbv.Close(false, Type.Missing, Type.Missing); excel.Quit(); //word.Quit(); } else { MessageBox.Show("Выберитие файл шаблона и файл с данными"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static int[,] добавитьФайлToolStripMenuItem_Click(System.Windows.Forms.TextBox textBox, System.Windows.Forms.ComboBox comboBox, System.Windows.Forms.ListBox listBox, System.Windows.Forms.OpenFileDialog openFileDialog1, int[,] Intron, System.Windows.Forms.Label Label) { if (Label.Text == "0") //на открытие { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog1.Filter = "text files(*.doc; *.docx)| *.doc; *.docx"; if (openFileDialog1.ShowDialog() == DialogResult.OK) //Открытие диалогового окна для открытия файла { S_namefiledirect = openFileDialog1.FileName; //Сохранение в переменную пути к выбранному фалу S_namefile = openFileDialog1.SafeFileName; //Сохранение в переменную имени выбранного файла S_namefile = S_namefile.Remove(S_namefile.IndexOf(".docx")); S_wordapp = new Word.Application(); //Создаем объект Word - равносильно запуску Word. S_wordapp.Visible = false; Object filename = S_namefiledirect; S_worddocument = S_wordapp.Documents.Open(ref filename); //Открываем конкретный существующий word документ из нужной директории. Object begin = Type.Missing; //В документе определяем диапазон,вызовом метода Range Object end = Type.Missing; //с передачей ему начального Word.Range wordrange = S_worddocument.Range(ref begin, ref end); //и конечного значений позиций символов. wordrange.Copy(); //Копирование в буфер обмена. S_text = Clipboard.GetText(); //Сохранение в переменную скопированного текста if (S_Osnova != S_STD) { System.IO.File.WriteAllText((S_STD + "/" + S_namefile + ".txt"), S_text); //Создание текстового файла txt и запись в него текста из буфера обмена System.IO.File.WriteAllText((S_Osnova + "/" + "The table of semantic fragments" + "/" + S_namefile + ".txt"), ""); //Создание текстового файла для таблиц смысловых фрагментов comboBox.Items.Add(S_namefile); //Добавление в combobox1 имени файла, с которого мы скопировали текст comboBox.Text = S_namefile; //Надпись комбобокса меняется на имя файла listBox.Items.Clear(); //очистка листбкса S_nameFile.Add(S_namefile); //Добавление в список имени файла S_textFile.Add(S_text); //Добавление в список текста файла Intron = IvanLibrary.GiveMeBlockStructureWithRemainElements.StartWorking(S_Osnova + "/Text documents/" + S_namefile + ".txt", S_Osnova + "/The table of semantic fragments/" + S_namefile + ".txt", textBox); // <- Здесь был Ваня Vlad.b1(listBox, S_Osnova + "/The table of semantic fragments/" + S_namefile + ".txt"); Object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges; Object originalFormat = Word.WdOriginalFormat.wdWordDocument; Object routeDocument = Type.Missing; S_wordapp.Quit(ref saveChanges, ref originalFormat, ref routeDocument); // Закрытие файла S_wordapp = null; } if (S_Osnova == S_STD) { System.IO.File.WriteAllText((S_STD + "/" + S_namefile + ".txt"), S_text); //Создание текстового файла txt и запись в него текста из буфера обмена System.IO.File.WriteAllText((S_Dobavl + "/" + "The table of semantic fragments" + "/" + S_namefile + ".txt"), ""); //Создание текстового файла для таблиц смысловых фрагментов comboBox.Items.Add(S_namefile); //Добавление в combobox1 имени файла, с которого мы скопировали текст comboBox.Text = S_namefile; //Надпись комбобокса меняется на имя файла listBox.Items.Clear(); //очистка листбкса S_nameFile.Add(S_namefile); //Добавление в список имени файла S_textFile.Add(S_text); //Добавление в список текста файла Intron = IvanLibrary.GiveMeBlockStructureWithRemainElements.StartWorking(S_Dobavl + "/Text documents/" + S_namefile + ".txt", S_Dobavl + "/The table of semantic fragments/" + S_namefile + ".txt", textBox); // <- Здесь был Ваня Vlad.b1(listBox, S_Dobavl + "/The table of semantic fragments/" + S_namefile + ".txt"); Object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges; Object originalFormat = Word.WdOriginalFormat.wdWordDocument; Object routeDocument = Type.Missing; S_wordapp.Quit(ref saveChanges, ref originalFormat, ref routeDocument); // Закрытие файла S_wordapp = null; } } } else if (Label.Text == "1") //на создание { OpenFileDialog openFileDialog2 = new OpenFileDialog(); openFileDialog1.Filter = "text files(*.doc; *.docx)| *.doc; *.docx"; if (openFileDialog1.ShowDialog() == DialogResult.OK) //Открытие диалогового окна для открытия файла { S_namefiledirect = openFileDialog1.FileName; //Сохранение в переменную пути к выбранному фалу S_namefile = openFileDialog1.SafeFileName; //Сохранение в переменную имени выбранного файла S_namefile = S_namefile.Remove(S_namefile.IndexOf(".docx")); S_wordapp = new Word.Application(); //Создаем объект Word - равносильно запуску Word. S_wordapp.Visible = false; Object filename = S_namefiledirect; S_worddocument = S_wordapp.Documents.Open(ref filename); //Открываем конкретный существующий word документ из нужной директории. Object begin = Type.Missing; //В документе определяем диапазон,вызовом метода Range Object end = Type.Missing; //с передачей ему начального Word.Range wordrange = S_worddocument.Range(ref begin, ref end); //и конечного значений позиций символов. wordrange.Copy(); //Копирование в буфер обмена. S_text = Clipboard.GetText(); //Сохранение в переменную скопированного текста if (S_Osnova != S_STD) { System.IO.File.WriteAllText((S_STD + "/" + S_namefile + ".txt"), S_text); //Создание текстового файла txt и запись в него текста из буфера обмена System.IO.File.WriteAllText((S_Osnova + "/" + "The table of semantic fragments" + "/" + S_namefile + ".txt"), ""); //Создание текстового файла для таблиц смысловых фрагментов comboBox.Items.Add(S_namefile); //Добавление в combobox1 имени файла, с которого мы скопировали текст comboBox.Text = S_namefile; //Надпись комбобокса меняется на имя файла listBox.Items.Clear(); //очистка листбкса S_nameFile.Add(S_namefile); //Добавление в список имени файла S_textFile.Add(S_text); //Добавление в список текста файла Intron = IvanLibrary.GiveMeBlockStructureWithRemainElements.StartWorking(S_Osnova + "/Text documents/" + S_namefile + ".txt", S_Osnova + "/The table of semantic fragments/" + S_namefile + ".txt", textBox); // <- Здесь был Ваня Vlad.b1(listBox, S_Osnova + "/The table of semantic fragments/" + S_namefile + ".txt"); Object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges; Object originalFormat = Word.WdOriginalFormat.wdWordDocument; Object routeDocument = Type.Missing; S_wordapp.Quit(ref saveChanges, ref originalFormat, ref routeDocument); // Закрытие файла S_wordapp = null; } if (S_Osnova == S_STD) { System.IO.File.WriteAllText((S_STD + "/" + S_namefile + ".txt"), S_text); //Создание текстового файла txt и запись в него текста из буфера обмена System.IO.File.WriteAllText((S_Dobavl + "/" + "The table of semantic fragments" + "/" + S_namefile + ".txt"), ""); //Создание текстового файла для таблиц смысловых фрагментов comboBox.Items.Add(S_namefile); //Добавление в combobox1 имени файла, с которого мы скопировали текст comboBox.Text = S_namefile; //Надпись комбобокса меняется на имя файла listBox.Items.Clear(); //очистка листбкса S_nameFile.Add(S_namefile); //Добавление в список имени файла S_textFile.Add(S_text); //Добавление в список текста файла Intron = IvanLibrary.GiveMeBlockStructureWithRemainElements.StartWorking(S_Dobavl + "/Text documents/" + S_namefile + ".txt", S_Dobavl + "/The table of semantic fragments/" + S_namefile + ".txt", textBox); // <- Здесь был Ваня Vlad.b1(listBox, S_Dobavl + "/The table of semantic fragments/" + S_namefile + ".txt"); Object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges; Object originalFormat = Word.WdOriginalFormat.wdWordDocument; Object routeDocument = Type.Missing; S_wordapp.Quit(ref saveChanges, ref originalFormat, ref routeDocument); // Закрытие файла S_wordapp = null; } } } return(Intron); }