public void SetHeaderInfo(List <string> headerInfo) { try { //string dateTested = headerInfo[0].ToString() == "" ? "" : ((DateTime)headerInfo[0]).ToShortDateString(); WordDoc.Sections[1].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Find.Execute("<date tested>", true, true, false, false, false, true, 1, false, headerInfo[0], 2, false, false, false, false); WordDoc.Sections[1].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Find.Execute("<tested by>", true, true, false, false, false, true, 1, false, headerInfo[1], 2, false, false, false, false); WordDoc.Sections[1].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Find.Execute("<check by>", true, true, false, false, false, true, 1, false, headerInfo[2], 2, false, false, false, false); } catch (Exception err) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nHardCopy Set_Header_Info -- {err.Source}; {err.TargetSite}\n{err.Message}\n"); sw.Close(); if (WordDoc != null) { WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); } if (WordApp != null) { WordApp.Quit(); } throw; } }
/// <summary> /// Implements the OnConnection method of the IDTExtensibility2 interface. /// Receives notification that the Add-in is being loaded. /// </summary> /// <param term='application'> /// Root object of the host application. /// </param> /// <param term='connectMode'> /// Describes how the Add-in is being loaded. /// </param> /// <param term='addInInst'> /// Object representing this Add-in. /// </param> /// <seealso class='IDTExtensibility2' /> public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom) { string strAppName = (string)application.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, application, null); if (strAppName == "Microsoft Word") { appThis = new WordApp(application); } else if (strAppName == "Microsoft Excel") { appThis = new ExcelApp(application); } else if (strAppName == "Microsoft Publisher") { appThis = new PubApp(application); } else if (strAppName == "Microsoft Access") { appThis = new AccessApp(application); } else { string strError = String.Format("The '{0}' application is not supported!", strAppName); System.Windows.Forms.MessageBox.Show(strError, OfficeApp.cstrCaption); throw new Exception(strError); } if (connectMode != ext_ConnectMode.ext_cm_Startup) { OnStartupComplete(ref custom); } }
/// <summary> /// insert standard job information to test report (work order number, test condition, part number, date code) /// </summary> public void Set_Job_Info(string structureTitle = "") { try { WordApp.Selection.Find.Execute("<wo number>", true, true, false, false, false, true, 1, false, WorkOrderNumber, 2, false, false, false, false); WordApp.Selection.Find.Execute("<condition>", true, true, false, false, false, true, 1, false, TestCondition, 2, false, false, false, false); WordApp.Selection.Find.Execute("<part number>", true, true, false, false, false, true, 1, false, PartNumber, 2, false, false, false, false); WordApp.Selection.Find.Execute("<date code>", true, true, false, false, false, true, 1, false, DateCode, 2, false, false, false, false); WordApp.Selection.Find.Execute("<structure title>", true, true, false, false, false, true, 1, false, structureTitle, 2, false, false, false, false); } catch (Exception err) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nReport Set_Job_Info -- {err.Source}; {err.TargetSite}\n{err.Message}\n"); sw.Close(); if (WordDoc != null) { WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); } if (WordApp != null) { WordApp.Quit(); } throw; } }
public void Dispose() { //throw new NotImplementedException(); try { Console.WriteLine("Closing Word application"); WordApp.Quit(SaveChanges: false); } catch (Exception) { Console.WriteLine("Error closing Word application. Kill winword.exe manually."); } }
public void Close_Document() { // save updated document to correct work order number directory // setup options for closing original template document object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; object originalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat; object routeDocument = false; // close original template document without saving changes and quit the word app WordDoc.Close(saveOption, originalFormat, routeDocument); WordApp.Quit(); }
/// <summary> /// Performs basic validation on the file being analyzed by this <see cref="FileAnalyzer" />. /// </summary> /// <returns>A <see cref="FileValidationResult" /> object representing the result of validation.</returns> public override FileValidationResult Validate() { try { using (WordApp app = new WordApp()) { app.Open(File); } return(FileValidationResult.Pass); } catch (COMException ex) { LogWarn("File failed to open: " + ex.Message); return(FileValidationResult.Fail(ex.Message)); } }
public void Underline_Serial_Number_Titles() { try { for (int i = 2; i <= WordDoc.Tables.Count; i += 2) { var table = WordDoc.Tables[i]; int row = 2; for (int j = 0; j < 2; j++) { Word.Cell cell = table.Cell(row, 1); int wordCount = cell.Range.Words.Count; for (int k = 1; k < wordCount; k++) { if (cell.Range.Words[k].Text == "S" && cell.Range.Words[k + 1].Text == "/") { while (cell.Range.Words[k].Text != "\r" && k != wordCount) { cell.Range.Words[k++].Font.Underline = Word.WdUnderline.wdUnderlineSingle; } } } row = 5; } } } catch (Exception err) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nReport Underline_Serial_Number_Titles -- {err.Source}; {err.TargetSite}\n{err.Message}\n"); sw.Close(); if (WordDoc != null) { WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); } if (WordApp != null) { WordApp.Quit(); } throw; } }
public static void FindString(object info) { ReplaceInFiles.ReplaceFileInfo replaceFileInfo = (ReplaceInFiles.ReplaceFileInfo)info; WordApp app = GetWordApplication(); foreach (string file in replaceFileInfo.files) { Word.Document doc = app.APP.Documents.Open(file, ref Nothing, true, 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); int foundCount = FindText(doc, replaceFileInfo.searchText); replaceFileInfo.mainForm.SetRichBoxText(string.Format("在文件【{0}】中找到【{1}】处【{2}】。 ", Path.GetFileName(file), foundCount, replaceFileInfo.searchText)); doc.Saved = true; doc.Close(); } if (app.Type == WordAPPType.NEW) { app.APP.Quit(); } replaceFileInfo.mainForm.SetRichBoxText("查找结束!"); replaceFileInfo.mainForm.SetStatus(true); }
public static void ReplaceString(object info) { ReplaceInFiles.ReplaceFileInfo replaceFileInfo = (ReplaceInFiles.ReplaceFileInfo)info; WordApp app = GetWordApplication(); foreach (string file in replaceFileInfo.files) { Word.Document doc = app.APP.Documents.Open(file, ref Nothing, true, 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); ReplaceAll(doc, replaceFileInfo.searchText, replaceFileInfo.replaceText); replaceFileInfo.mainForm.SetRichBoxText(string.Format("文件【{0}】替换成功。 ", Path.GetFileName(file))); string resultPath = Path.Combine(replaceFileInfo.resultFolder, Path.GetFileName(file)); doc.SaveAs2(resultPath); doc.Close(); } if (app.Type == WordAPPType.NEW) { app.APP.Quit(); } replaceFileInfo.mainForm.SetRichBoxText(string.Format("替换结束!共计替换【{0}】个文件", replaceFileInfo.files.Count)); replaceFileInfo.mainForm.SetStatus(true); }
/// <summary> /// Gets information about a document, such as page count, title, and author. /// </summary> /// <returns>A <see cref="DocumentProperties" /> object.</returns> public override DocumentProperties GetProperties() { DocumentProperties properties = new DocumentProperties(File); try { using (WordApp app = new WordApp()) { WordDocument document = app.Open(File); // Page count must be calculated first - strange results otherwise properties.Pages = (short)document.ComputeStatistics(WdStatistic.wdStatisticPages); // Get the page orientation switch (document.PageSetup.Orientation) { case WdOrientation.wdOrientPortrait: properties.Orientation = Orientation.Portrait; break; case WdOrientation.wdOrientLandscape: properties.Orientation = Orientation.Landscape; break; } // Retrieve built-in document properties properties.Title = document.BuiltInDocumentProperties.Item["Title"].Value; properties.Author = document.BuiltInDocumentProperties.Item["Author"].Value; properties.Application = document.BuiltInDocumentProperties.Item["Application Name"].Value; } } catch (COMException ex) { // Log the error, then return whatever properties have been collected. LogWarn("Failure retrieving properties: " + ex.Message); } return(properties); }
/// <summary> /// Implements the OnConnection method of the IDTExtensibility2 interface. /// Receives notification that the Add-in is being loaded. /// </summary> /// <param term='application'> /// Root object of the host application. /// </param> /// <param term='connectMode'> /// Describes how the Add-in is being loaded. /// </param> /// <param term='addInInst'> /// Object representing this Add-in. /// </param> /// <seealso class='IDTExtensibility2' /> public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom) { string strAppName = (string)application.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, application, null); if (strAppName == "Microsoft Word") appThis = new WordApp(application); else if (strAppName == "Microsoft Excel") appThis = new ExcelApp(application); else if (strAppName == "Microsoft Publisher") appThis = new PubApp(application); else if (strAppName == "Microsoft Access") appThis = new AccessApp(application); else { string strError = String.Format("The '{0}' application is not supported!", strAppName); System.Windows.Forms.MessageBox.Show(strError, cstrCaption); throw new Exception(strError); } if (connectMode != Extensibility.ext_ConnectMode.ext_cm_Startup) { OnStartupComplete(ref custom); } }
private static WordApp GetWordApplication() { Word.Application winObj = null; WordAPPType type = WordAPPType.GET; try { winObj = (Word.Application)Marshal.GetActiveObject("Word.Application"); type = WordAPPType.GET; } catch (Exception) { if (winObj == null) { winObj = new Word.Application(); type = WordAPPType.NEW; } } WordApp wordApp = new WordApp(); wordApp.Type = type; wordApp.APP = winObj; return(wordApp); }
static void Main(string[] args) { object oMissing = Type.Missing; //System.Reflection.Missing.Value; Word.Application WordApp = null; Word.Document Document = null; Word.Table Table = null; string CurrentDirectory = System.IO.Directory.GetCurrentDirectory(), tmpString; CurrentDirectory = CurrentDirectory.Substring(0, CurrentDirectory.LastIndexOf("bin", CurrentDirectory.Length - 1)); object InputFileName, OutputFileName, tmpObject; try { try { try { WordApp = (Word.Application)Marshal.GetActiveObject("Word.Application"); } catch (COMException eException) { if (eException.ErrorCode == -2147221021) { WordApp = new Word.Application(); } } WordApp.Visible = true; #if TEST_BOOKMARK InputFileName = CurrentDirectory + "Word_tst.doc"; Document = WordApp.Documents.Open(ref InputFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); if (Document.Bookmarks.Count > 0) { tmpString = "MyBookmark"; if (Document.Bookmarks.Exists(tmpString)) { tmpObject = tmpString; #if TEST_BOOKMARK_BY_BOOKMARKS_COLLECTION Document.Bookmarks.Item(ref tmpObject).Select(); #else object What = Word.WdGoToItem.wdGoToBookmark; WordApp.Selection.GoTo(/*What*/ ref What, /*Which*/ ref oMissing, /*Count*/ ref oMissing, /*Name*/ ref tmpObject); #endif WordApp.Selection.Text = "1234567890"; } } OutputFileName = CurrentDirectory + "Word_tst_out.doc"; if (File.Exists(OutputFileName.ToString())) { File.Delete(OutputFileName.ToString()); } Document.SaveAs(ref OutputFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); Document.Close(ref oMissing, ref oMissing, ref oMissing); #endif Document = WordApp.Documents.Add(ref oMissing, ref oMissing); int index = 0, rows = 3, columns = 2; Table = Document.Tables.Add(WordApp.Selection.Range, rows + 1, columns); Table.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; Table.Range.Bold = 1; for (int i = 0; i < columns; i++) { Table.Cell(0, i + 1).Range.InsertAfter(i.ToString()); } for (int j = 1; j <= rows; j++) { Table.Rows.Item(j + 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; Table.Rows.Item(j + 1).Range.Bold = 0; for (int i = 0; i < columns; i++) { Table.Cell(j + 1, i + 1).Range.InsertAfter(index.ToString()); index++; } } OutputFileName = CurrentDirectory + "test_out.doc"; if (File.Exists(OutputFileName.ToString())) { File.Delete(OutputFileName.ToString()); } Document.SaveAs(ref OutputFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); Document.Close(ref oMissing, ref oMissing, ref oMissing); } catch (COMException eException) { string tmp = eException.GetType().FullName + Environment.NewLine + "ErrorCode: " + eException.ErrorCode + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + "StackTrace:" + Environment.NewLine + eException.StackTrace; Console.WriteLine(tmp); } catch (ArgumentException eException) { string tmp = eException.GetType().FullName + Environment.NewLine + "ParamName: " + eException.ParamName + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + "StackTrace:" + Environment.NewLine + eException.StackTrace; Console.WriteLine(tmp); } catch (Exception eException) { string tmp = eException.GetType().FullName + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + "StackTrace:" + Environment.NewLine + eException.StackTrace; Console.WriteLine(tmp); } } finally { if (Table != null) { Marshal.ReleaseComObject(Table); Table = null; } if (Document != null) { Marshal.ReleaseComObject(Document); Document = null; } if (WordApp != null) { WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); Marshal.ReleaseComObject(WordApp); WordApp = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.GetTotalMemory(true); //GC.SuppressFinalize(this); } }
public void Set_Single_Structure_Data_Row(string serialNumber, string location, List <string> dataRow, string acceptReject, bool distinctSn, int dataPerPage) { try { if (DataRowCount == dataPerPage) { Add_Page(); } Word.Table dataTable = WordDoc.Tables[DataTableIndex]; if (!distinctSn) { dataTable.Cell(2, 1).Range.Text += $"S/N {serialNumber} Loc {location}"; dataTable.Cell(5, 1).Range.Text += $"S/N {serialNumber} Loc {location}"; } else { dataTable.Cell(2, 1).Range.Text += serialNumber; dataTable.Cell(5, 1).Range.Text += serialNumber; } int row = 2, column = 2; foreach (string value in dataRow) { string printValue = string.Empty; if (string.IsNullOrEmpty(value)) { printValue = "###"; } else { printValue = value; if (value.Contains("^")) { printValue = value.Replace('^', ' '); } if (value.Contains("\n")) { printValue = value.Replace('\n', '/'); } } dataTable.Cell(row, column++).Range.Text += $"{printValue}"; if (column == 8 && row == 2) { row = 5; column = 2; } } if (acceptReject == "A") { dataTable.Cell(row, column).Range.Text += "Accept"; } else if (acceptReject == "R") { dataTable.Cell(row, column).Range.Text += "Non-Conformance"; } else if (!string.IsNullOrEmpty(acceptReject) && acceptReject.Contains("*")) { dataTable.Cell(row, column).Range.Text += "Customer-eval"; } else { dataTable.Cell(row, column).Range.Text += "###"; } //data_table.Cell(row, column).Range.Text += $"{accept_reject}"; DataRowCount++; } catch (Exception ex) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nReport Set_Single_Structure_Data_Row -- {ex.Source}; {ex.TargetSite}\n{ex.Message}\n"); sw.Close(); if (WordDoc != null) { WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); } if (WordApp != null) { WordApp.Quit(); } throw; } }
public void SetRequirements(List <string> requirements) { try { var requirementsTable = WordDoc.Tables[3]; int column = 2; foreach (string requirement in requirements) { //if (requirementsTable.Cell(1, column).Range.Text.StartsWith("N/A")) //{ // column++; // continue; //} if (string.IsNullOrEmpty(requirement)) { column++; } else if (requirement == "collapsed") { requirementsTable.Cell(1, column - 1).Merge(requirementsTable.Cell(1, column)); } else if (requirement.Contains("\n") && !requirement.ToLower().StartsWith("layer") && !requirement.ToLower().StartsWith("x:") && !requirement.ToLower().StartsWith("negative") && !requirement.ToLower().StartsWith("smear")) { // separate each requirement string[] reqSplit = requirement.Split('\n'); //List<string> reqList = new List<string>(); //string formatReq = ""; //foreach (string individualReq in reqSplit) //{ // string req = individualReq.Trim(); // formatReq += req; //} // split the current cell setting number of rows equal to numnber of requirements requirementsTable.Cell(1, column).Split(reqSplit.Length, 1); int row = 1; foreach (string individualReq in reqSplit) { string req = individualReq.Trim(); if (req.Contains(" (")) { req = req.Replace(" (", "\n("); } requirementsTable.Cell(row++, column).Range.Text = req; } column++; } else { string req = requirement; if (req.Contains(" (")) { req = req.Replace(" (", "\n("); } requirementsTable.Cell(1, column++).Range.Text = req; } } } catch (Exception err) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nHardCopy Set_Requirements -- {err.Source}; {err.TargetSite}\n{err.Message}\n"); sw.Close(); if (WordDoc != null) { WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); } if (WordApp != null) { WordApp.Quit(); } throw; } }
public async Task SetData() { try { await using (var db = new DigitalDatasheetContext()) { // check locations for multiple coupon set condition var locations = db.JobDataTable .Where(data => data.WorkOrderNumber.Equals(WorkOrderNumber) && data.TestCondition.Equals(TestCondition) && data.TestPerformedOn.Equals(TestPerformedOn)) .Select(r => r.Location) .Distinct(); if (locations.Count() > 1) { WordApp.Selection.Find.Execute("<cpn set>", true, true, false, false, false, true, 1, false, "Multiple Coupon Set", 2, false, false, false, false); } else { WordApp.Selection.Find.Execute("<cpn set>", true, true, false, false, false, true, 1, false, "", 2, false, false, false, false); } var records = await db.JobDataTable .Where(data => data.WorkOrderNumber.Equals(WorkOrderNumber) && data.TestCondition.Equals(TestCondition) && data.TestPerformedOn.Equals(TestPerformedOn)) .OrderBy(data => data.StructureOrder) .ThenBy(data => data.Row) .ToListAsync(); var dataTable = WordDoc.Tables[2]; // create inital set table based on number of structures there are // base table will have one row for each structure and below each structure, one row for measurements var structureList = records .OrderBy(r => r.StructureOrder) .Select(r => new { r.StructureTitle }) .Distinct() .ToList(); for (int i = 1; i < structureList.Count; i++) { dataTable.Rows.Add(dataTable.Rows[dataTable.Rows.Count]); dataTable.Rows.Add(dataTable.Rows[dataTable.Rows.Count]); dataTable.Cell(dataTable.Rows.Count - 1, 1).Merge(dataTable.Cell(dataTable.Rows.Count - 1, 20)); } //data_table.Cell(1, 1).Range.Text = structure_list[0]; // set row for structure titles to same format (center vertical and horizontal alignment and font) for (int i = 3; i < dataTable.Rows.Count; i += 2) { dataTable.Cell(i, 1).Range.Font = dataTable.Cell(1, 1).Range.Font; dataTable.Cell(i, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; } int endRow = dataTable.Rows.Count; // loop through each structure starting from the end for (int i = structureList.Count - 1; i >= 0; i--) { var recordSet = records .Where(r => r.StructureTitle == structureList[i].StructureTitle) .OrderBy(r => r.Row) .ToList(); // set last structure title row to correct structure dataTable.Cell(endRow - 1, 1).Range.Text = structureList[i].StructureTitle; // loop through each location/serial number combo for each structure starting from the end for (int j = recordSet.Count - 1; j >= 0; j--) { // if serial number has associated location add location and set font color to red if (string.IsNullOrEmpty(recordSet[j].Location)) { // set first column of row to serial number dataTable.Cell(endRow, 1).Range.Text = recordSet[j].SerialNumber; dataTable.Cell(endRow, 1).Range.Font.Color = Word.WdColor.wdColorBlack; dataTable.Cell(endRow, 1).Shading.BackgroundPatternColor = Word.WdColor.wdColorWhite; } else { // set first column of row to location/serial number dataTable.Cell(endRow, 1).Range.Text = $"loc {recordSet[j].Location}\n{recordSet[j].SerialNumber}"; dataTable.Cell(endRow, 1).Range.Font.Color = Word.WdColor.wdColorBlack; dataTable.Cell(endRow, 1).Shading.BackgroundPatternColor = Word.WdColor.wdColorWhite; // set location font color to red int wordCount = dataTable.Cell(endRow, 1).Range.Words.Count; for (int k = 1; k < wordCount; k++) { Word.Range word = dataTable.Cell(endRow, 1).Range.Words[k]; if (word.Text.StartsWith("loc")) { while (dataTable.Cell(endRow, 1).Range.Words[k].Text != "\r" && k != wordCount) { dataTable.Cell(endRow, 1).Range.Words[k++].Font.Color = Word.WdColor.wdColorRed; } } } } // set remaining columns of row to measurements and observations List <string> dataRow = new List <string> { recordSet[j].HoleCuPlating, recordSet[j].ExternalConductor, recordSet[j].SurfaceCladCu, recordSet[j].WrapCu, recordSet[j].CapCu, recordSet[j].InternalCladCu, recordSet[j].MinEtchback, recordSet[j].MaxEtchback, recordSet[j].InternalAnnularRing, recordSet[j].ExternalAnnularRing, recordSet[j].Dielectric, recordSet[j].Wicking, recordSet[j].InnerlayerSeparation, recordSet[j].PlatingCrack, recordSet[j].PlatingVoid, recordSet[j].DelamBlisters, recordSet[j].LaminateVoidCrack, recordSet[j].AcceptReject }; // loop through data row setting columns to each value int column = 2; foreach (string data in dataRow) { if (string.IsNullOrEmpty(data)) { column++; continue; } if (column == 19) { column++; } // check if measurement starts with an R (if it does, set the cell background color to yellow and remove the R) if (column <= 13) { string newData = data; if (data.StartsWith("R")) { if (data.Contains("^")) { string[] splitData = data.Split('^'); newData = $"{splitData[1]}\n{splitData[0]}"; } newData = newData.Remove(newData.IndexOf('R'), 1); dataTable.Cell(endRow, column).Range.Text = newData; dataTable.Cell(endRow, column).Shading.BackgroundPatternColor = Word.WdColor.wdColorYellow; dataTable.Cell(endRow, 1).Shading.BackgroundPatternColor = Word.WdColor.wdColorYellow; } else if (data.Contains("^")) { string[] splitData = data.Split('^'); newData = $"{splitData[1]}\n{splitData[0]}"; dataTable.Cell(endRow, column).Range.Text = $"{newData}"; dataTable.Cell(endRow, column).Shading.BackgroundPatternColor = Word.WdColor.wdColorWhite; } else { dataTable.Cell(endRow, column).Range.Text = data; if (data == "N/A") { dataTable.Cell(endRow, column).Shading.BackgroundPatternColor = Word.WdColor.wdColorGray10; } else { dataTable.Cell(endRow, column).Shading.BackgroundPatternColor = Word.WdColor.wdColorWhite; } } } else { dataTable.Cell(endRow, column).Range.Text = data; if (data == "R") { dataTable.Cell(endRow, column).Shading.BackgroundPatternColor = Word.WdColor.wdColorYellow; dataTable.Cell(endRow, 1).Shading.BackgroundPatternColor = Word.WdColor.wdColorYellow; } else { dataTable.Cell(endRow, column).Shading.BackgroundPatternColor = Word.WdColor.wdColorWhite; } } column++; } // if this is the final row of the data list, do not add new row to word document if (j != 0) { dataTable.Rows.Add(dataTable.Rows[endRow]); } } endRow -= 2; } } } catch (Exception err) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nHardCopy Set_Data -- {err.Source}; {err.TargetSite}\n{err.Message}\n"); sw.Close(); if (WordDoc != null) { WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); } if (WordApp != null) { WordApp.Quit(); } throw; } }
public void Set_Multiple_Structure_Data_Rows(string serialNumber, List <string> locations, List <string> structureTitles, List <List <string> > dataRows, List <string> acceptRejects, bool distinctSn, int dataPerPage) { try { if (DataRowCount == dataPerPage) { Add_Page(); } Word.Table dataTable = WordDoc.Tables[DataTableIndex]; bool sameLocations = locations.Distinct().ToList().Count == 1; if (!distinctSn && sameLocations) { dataTable.Cell(2, 1).Range.Text += $"S/N {serialNumber} Loc {locations[0]}"; dataTable.Cell(5, 1).Range.Text += $"S/N {serialNumber} Loc {locations[0]}"; } else { dataTable.Cell(2, 1).Range.Text += $"S/N: {serialNumber}"; dataTable.Cell(5, 1).Range.Text += $"S/N: {serialNumber}"; } int row = 2, column = 2; string acceptReject = ""; for (int i = 0; i < 13; i++) { dataTable.Cell(row, column++).Range.Text += ""; if (column == 8 && row == 2) { row = 5; column = 2; } } for (int i = 0; i < structureTitles.Count; i++) { if (!sameLocations && !distinctSn) { dataTable.Cell(2, 1).Range.Text += $"{structureTitles[i]} Loc {locations[i]}"; dataTable.Cell(5, 1).Range.Text += $"{structureTitles[i]} Loc {locations[i]}"; } else { dataTable.Cell(2, 1).Range.Text += $"{structureTitles[i]}"; dataTable.Cell(5, 1).Range.Text += $"{structureTitles[i]}"; } row = 2; column = 2; foreach (string value in dataRows[i]) { string printValue = string.Empty; if (string.IsNullOrEmpty(value)) { printValue = "###"; } else { printValue = value; if (value.Contains("^")) { printValue = value.Replace('^', ' '); } if (value.Contains("\n")) { printValue = value.Replace('\n', '/'); } } dataTable.Cell(row, column++).Range.Text += $"{printValue}"; if (column == 8 && row == 2) { row = 5; column = 2; } } if (acceptRejects[i] == "A") { acceptReject = "Accept"; } else if (acceptRejects[i] == "R") { acceptReject = "Non-Conformance"; } else if (!string.IsNullOrEmpty(acceptReject) && acceptReject.Contains("*")) { acceptReject = "Customer-eval"; } else { acceptReject = "###"; } dataTable.Cell(row, column).Range.Text += $"{acceptReject}"; } row = 2; column = 1; for (int i = 0; i < 15; i++) { dataTable.Cell(row, column++).Range.Text += ""; if (column == 8 && row == 2) { row = 5; column = 1; } } DataRowCount += dataRows.Count; } catch (Exception ex) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nReport Set_Multiple_Structure_Data_Rows -- {ex.Source}; {ex.TargetSite}\n{ex.Message}\n"); sw.Close(); if (WordDoc != null) { WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); } if (WordApp != null) { WordApp.Quit(); } throw; } }
public async Task Save_And_Close(string customer) { try { //app.Visible = true; // get path to directory of current work order number and determine if it exists string letterFolder, fullDir, filePath; DateReceivedYear = await new AccessDb().GetJobYear(WorkOrderNumber); if (string.IsNullOrEmpty(DateReceivedYear)) { MessageBox.Show("Invalid date received for current job. Please check and make sure job information is correct.", "Job Date Error", MessageBoxButton.OK, MessageBoxImage.Error); WordApp.Visible = true; return; } Regex letterFolderRegex = new Regex(@"^[a-mA-M0-9]"); letterFolder = letterFolderRegex.IsMatch(customer) ? "_A to M" : "_N to Z"; fullDir = $@"test_report_complete_location"; //DirectoryInfo job_path = new DirectoryInfo(full_dir); if (!Directory.Exists(fullDir)) { MessageBox.Show("The current job folder does not exist. Please check and make sure this work order number is correct and has been logged.", "No Job Folder", MessageBoxButton.OK, MessageBoxImage.Exclamation); WordApp.Visible = true; return; } filePath = $@"{fullDir}\{WorkOrderNumber}_{TestConditionAbr}_{TestPerformedOn}_Metallographic_Examination_test_report_data_only.docx"; // determine if file already exists and ask before overwriting if (File.Exists(filePath)) { if (MessageBox.Show("Data only test report already exists. Saving current file will override existing test report. Would you like to continue and save anyway?", "File Already Exists", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No) { WordApp.Visible = true; return; } } WordDoc.SaveAs2(filePath); if (MessageBox.Show("Data only test report has been created and saved in job folder. Would you like to open it now?", "Open Test Report", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { try { // open directoruy containing data report Process.Start(fullDir); } catch (Exception) { } // open data report WordApp.Visible = true; } else { WordDoc.Close(); WordApp.Quit(); } } catch (Exception ex) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nReport Save_And_Close -- {ex.Source}; {ex.TargetSite}\n{ex.Message}\n"); sw.Close(); if (WordApp != null) { WordApp.Visible = true; } //if (WordDoc != null) // WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); //if (WordApp != null) // WordApp.Quit(); throw; } }
public void Set_Reject_Background_Color() { try { // set reject data background to yellow for (int i = 2; i <= WordDoc.Tables.Count; i += 2) { var table = WordDoc.Tables[i]; int row = 2, column = 2; for (int j = 0; j < 11; j++) { Word.Cell cell = table.Cell(row, column++); int wordCount = cell.Range.Words.Count; for (int k = 1; k < wordCount; k++) { Word.Range word = cell.Range.Words[k]; if (word.Text.StartsWith("R")) { word.Text = word.Text.Remove(0, 1); while (cell.Range.Words[k].Text != "\r" && k != wordCount) { cell.Range.Words[k++].Font.Shading.BackgroundPatternColor = Word.WdColor.wdColorYellow; } } } if (column == 8) { row = 5; column = 2; } } } // set "non-conformance" status background to yellow in accept/reject column for (int i = 2; i <= WordDoc.Tables.Count; i += 2) { var table = WordDoc.Tables[i]; Word.Cell cell = table.Cell(5, 8); int wordCount = cell.Range.Words.Count; for (int j = 1; j < wordCount; j++) { Word.Range word = cell.Range.Words[j]; if (word.Text == "Non" || word.Text == "-" || word.Text == "Conformance") { word.Font.Shading.BackgroundPatternColor = Word.WdColor.wdColorYellow; } } } } catch (Exception ex) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nReport Set_Reject_Background_Color -- {ex.Source}; {ex.TargetSite}\n{ex.Message}\n"); sw.Close(); if (WordDoc != null) { WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); } if (WordApp != null) { WordApp.Quit(); } throw; } }
public void Set_Requirements(List <string> requirements) { try { // check how many data tables there are to determine how many times you must set the requirements for (int i = 2; i <= WordDoc.Tables.Count; i += 2) { Word.Table dataTable = WordDoc.Tables[i]; int row = 3, column = 2, lastColumn = 8; foreach (string requirement in requirements) { if (string.IsNullOrEmpty(requirement)) { column++; } else { if (requirement.ToLower().StartsWith("layers")) { string reqText = requirement.Remove(0, requirement.IndexOf('\n') + 1); string formattedReq = reqText; if (reqText.Contains("\n")) { // separate each set of equal thickness layers on individual lines string[] setLayers = reqText.Split('\n'); formattedReq = $"Layers: {setLayers[0].Trim()}"; for (int k = 1; k < setLayers.Length; k++) { setLayers[k] = setLayers[k].Trim(); if (setLayers[k].ToLower().StartsWith("(stack") || setLayers[k].ToLower().StartsWith("stack")) { continue; } formattedReq += $"\nLayers: {setLayers[k]}"; } formattedReq += "\n(Stack-up)"; dataTable.Cell(row, column).Range.Text = formattedReq; column++; } else { dataTable.Cell(row, column++).Range.Text = $"Layers: {reqText}"; } //if (data_table.Cell(row-1, column).Range.Text.Contains("*")) // Set_Internal_Layers(data_table, formatted_req); } else { dataTable.Cell(row, column++).Range.Text = requirement; } } if (column == lastColumn && row == 3) { row = 6; column = 2; } } // after each requirement is set, go through and split rows where needed int tempRow = 6, tempColumn = 7, tempLastColumn = 1; //foreach (string requirement in requirements) for (int j = requirements.Count - 1; j >= 0; j--) { string reqText = requirements[j]; if (!string.IsNullOrEmpty(reqText)) { if (reqText == "collapsed") { dataTable.Cell(tempRow, tempColumn).Range.Text = ""; dataTable.Cell(tempRow, tempColumn - 1).Merge(dataTable.Cell(tempRow, tempColumn)); //tempLastColumn--; //tempColumn--; //continue; } else if (reqText.Contains("\n") && !reqText.ToLower().StartsWith("layer") && !reqText.ToLower().StartsWith("x:") && !reqText.ToLower().StartsWith("negative") && !reqText.ToLower().StartsWith("smear")) { // clear text from requirement cell dataTable.Cell(tempRow, tempColumn).Range.Text = ""; // separate each requirement string[] reqSplit = reqText.Split('\n'); // split the current cell setting number of rows equal to numnber of requirements dataTable.Cell(tempRow, tempColumn).Split(reqSplit.Length, 1); int splitRow = tempRow; foreach (string individual_req in reqSplit) { string req = individual_req.Trim(); dataTable.Cell(splitRow, tempColumn).Range.Text = req; dataTable.Cell(splitRow, tempColumn).Height = 0.1f; splitRow++; } } } tempColumn--; if (tempColumn == tempLastColumn && tempRow == 6) { tempRow = 3; tempColumn = 7; } } row = 3; column = 2; lastColumn = 8; for (int j = 0; j < 12; j++) { string reqText = dataTable.Cell(row, column).Range.Text; if (string.IsNullOrEmpty(reqText)) { continue; } if (reqText.Contains(" (")) { reqText = reqText.Replace(" (", "\n("); int lastReturnIndex = reqText.LastIndexOf("\r"); if (lastReturnIndex != -1) { reqText = reqText.Remove(lastReturnIndex); } dataTable.Cell(row, column).Range.Text = reqText; } column++; if (column == lastColumn && row == 3) { row = 6; column = 2; } } } } catch (Exception ex) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nReport Set_Requirements -- {ex.Source}; {ex.TargetSite}\n{ex.Message}\n"); sw.Close(); if (WordDoc != null) { WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); } if (WordApp != null) { WordApp.Quit(); } throw; } }
public void Set_Internal_Layers(string internalLayers) { try { for (int i = 2; i <= WordDoc.Tables.Count; i += 2) { if (string.IsNullOrEmpty(internalLayers)) { return; } Word.Cell cell = WordDoc.Tables[i].Cell(2, 7); string formattedInternalLayers = internalLayers.Remove(0, internalLayers.IndexOf(':') + 1); string[] format_split = formattedInternalLayers.Split(';'); string newLayersMeasurement = ""; foreach (string layer in format_split) { string[] layerSections = layer.Trim().Split(':'); string layerNumbers = layerSections[0].Trim(); if (!layerNumbers.Contains("&")) { int lastCommaIndex = layerNumbers.LastIndexOf(","); if (lastCommaIndex >= 0) { layerNumbers = layerNumbers.Remove(lastCommaIndex, 1).Insert(lastCommaIndex, " &"); } } string layerWeightMeasurement = layerSections[1].Trim(); layerWeightMeasurement = layerWeightMeasurement.Replace("oz", "oz.,"); newLayersMeasurement += $"\nLayers {layerNumbers}:\n{layerWeightMeasurement}\n"; } if (newLayersMeasurement.ToLower().Contains("plus")) { newLayersMeasurement.Replace("plus", "+"); } cell.Range.Text = newLayersMeasurement; // underline top section of each set of layers int wordCount = cell.Range.Words.Count; //MessageBox.Show($"{word_count}"); for (int k = 1; k < wordCount; k++) { if (cell.Range.Words[k].Text.ToLower().StartsWith("layer")) { //MessageBox.Show($"{cell.Range.Words[k].Text}"); while (cell.Range.Words[k].Text != "\r" && k != wordCount) { cell.Range.Words[k++].Font.Underline = Word.WdUnderline.wdUnderlineSingle; } } } } } catch (Exception ex) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nReport Set_Internal_Layers -- {ex.Source}; {ex.TargetSite}\n{ex.Message}\n"); sw.Close(); if (WordDoc != null) { WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); } if (WordApp != null) { WordApp.Quit(); } throw; } }
public void Dispose() { WordDocument?.Close(WdSaveOptions.wdDoNotSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, false); WordApp?.Quit(); }
/// <summary> /// insert standard job information to test report (work order number, test condition, part number, date code) /// </summary> public void SetJobInfo(Form jobInfo) { try { int testPerformedOnNum = 0; switch (TestPerformedOn) { case "Coupons": testPerformedOnNum = 1; break; case "BareBoards": testPerformedOnNum = 2; break; case "CustomerMounts": testPerformedOnNum = 3; break; case "AssembledBoards": testPerformedOnNum = 4; break; case "Class2Assessment": testPerformedOnNum = 5; break; } for (int i = 1; i <= 5; i++) { if (testPerformedOnNum == i) { WordApp.Selection.Find.Execute($"<{i}>", true, true, false, false, false, true, 1, false, "X", 2, false, false, false, false); } else { WordApp.Selection.Find.Execute($"<{i}>", true, true, false, false, false, true, 1, false, "_", 2, false, false, false, false); } if (testPerformedOnNum == 3) { WordApp.Selection.Find.Execute("<#>", true, true, false, false, false, true, 1, false, jobInfo.CustomerMountQty, 2, false, false, false, false); } else { WordApp.Selection.Find.Execute("<#>", true, true, false, false, false, true, 1, false, "_", 2, false, false, false, false); } } WordApp.Selection.Find.Execute("<wo number>", true, true, false, false, false, true, 1, false, WorkOrderNumber, 2, false, false, false, false); WordApp.Selection.Find.Execute("<part number>", true, true, false, false, false, true, 1, false, jobInfo.PartNumber, 2, false, false, false, false); WordApp.Selection.Find.Execute("<lot number>", true, true, false, false, false, true, 1, false, jobInfo.LotNumber, 2, false, false, false, false); WordApp.Selection.Find.Execute("<customer>", true, true, false, false, false, true, 1, false, jobInfo.Customer, 2, false, false, false, false); WordApp.Selection.Find.Execute("<date code>", true, true, false, false, false, true, 1, false, jobInfo.DateCode, 2, false, false, false, false); WordApp.Selection.Find.Execute("<specification 1>", true, true, false, false, false, true, 1, false, jobInfo.Specification1, 2, false, false, false, false); WordApp.Selection.Find.Execute("<specification 2>", true, true, false, false, false, true, 1, false, jobInfo.Specification2, 2, false, false, false, false); WordApp.Selection.Find.Execute("<board type>", true, true, false, false, false, true, 1, false, jobInfo.BoardType, 2, false, false, false, false); WordApp.Selection.Find.Execute("<test procedure>", true, true, false, false, false, true, 1, false, jobInfo.TestProcedure, 2, false, false, false, false); //string drawingProvided = jobInfo.DrawingProvided == 1 ? "YES" : "NO"; WordApp.Selection.Find.Execute("<drawing provided>", true, true, false, false, false, true, 1, false, jobInfo.DrawingProvided == 1 ? "YES" : "NO", 2, false, false, false, false); WordApp.Selection.Find.Execute("<evaluated by>", true, true, false, false, false, true, 1, false, jobInfo.EvaluatedBy, 2, false, false, false, false); //string dateEval = jobInfo[14].ToString() == "" ? "" : ((DateTime)jobInfo[14]).ToShortDateString(); WordApp.Selection.Find.Execute("<date eval>", true, true, false, false, false, true, 1, false, jobInfo.DateEvaluated.HasValue ? (jobInfo.DateTested as DateTime?).Value.ToShortDateString() : string.Empty, 2, false, false, false, false); if (TestConditionAbr == "TS") { WordApp.Selection.Find.Execute("<time in>", true, true, false, false, false, true, 1, false, jobInfo.BakeTimeIn, 2, false, false, false, false); WordApp.Selection.Find.Execute("<time out>", true, true, false, false, false, true, 1, false, jobInfo.BakeTimeOut, 2, false, false, false, false); WordApp.Selection.Find.Execute("<hrs>", true, true, false, false, false, true, 1, false, jobInfo.TotalTime, 2, false, false, false, false); WordApp.Selection.Find.Execute("<temp>", true, true, false, false, false, true, 1, false, jobInfo.TestTemp, 2, false, false, false, false); WordApp.Selection.Find.Execute("<floats>", true, true, false, false, false, true, 1, false, $"{jobInfo.SolderFloats}X", 2, false, false, false, false); } } catch (Exception err) { sw = new StreamWriter(ErrorLogFilePath, true); sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nHardCopy Set_Job_Info -- {err.Source}; {err.TargetSite}\n{err.Message}\n"); sw.Close(); if (WordDoc != null) { WordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, false); } if (WordApp != null) { WordApp.Quit(); } throw; } }
/// <summary> Returns the type of Office Application that is hosting the VBE. </summary> public static IHostApplication HostApplication(this IVBE vbe) { var host = Path.GetFileName(System.Windows.Forms.Application.ExecutablePath).ToUpperInvariant(); //This needs the VBE as a ctor argument. if (host.Equals("SLDWORKS.EXE")) { return(new SolidWorksApp(vbe)); } //The rest don't. if (HostAppMap.ContainsKey(host)) { return((IHostApplication)Activator.CreateInstance(HostAppMap[host])); } //Guessing the above will work like 99.9999% of the time for supported applications. var project = vbe.ActiveVBProject; { if (project.IsWrappingNullReference) { const int ctlViewHost = 106; var commandBars = vbe.CommandBars; var hostAppControl = commandBars.FindControl(ControlType.Button, ctlViewHost); { IHostApplication result; if (hostAppControl.IsWrappingNullReference) { result = null; } else { switch (hostAppControl.Caption) { case "Microsoft Excel": result = new ExcelApp(); break; case "Microsoft Access": result = new AccessApp(); break; case "Microsoft Word": result = new WordApp(); break; case "Microsoft PowerPoint": result = new PowerPointApp(vbe); break; case "Microsoft Outlook": result = new OutlookApp(); break; case "Microsoft Project": result = new ProjectApp(); break; case "Microsoft Publisher": result = new PublisherApp(); break; case "Microsoft Visio": result = new VisioApp(); break; case "AutoCAD": result = new AutoCADApp(); break; case "CorelDRAW": result = new CorelDRAWApp(); break; case "SolidWorks": result = new SolidWorksApp(vbe); break; default: result = null; break; } } return(result); } } var references = project.References; { foreach (var reference in references.Where(reference => (reference.IsBuiltIn && reference.Name != "VBA") || (reference.Name == "AutoCAD"))) { switch (reference.Name) { case "Excel": return(new ExcelApp(vbe)); case "Access": return(new AccessApp()); case "Word": return(new WordApp(vbe)); case "PowerPoint": return(new PowerPointApp(vbe)); case "Outlook": return(new OutlookApp()); case "MSProject": return(new ProjectApp()); case "Publisher": return(new PublisherApp()); case "Visio": return(new VisioApp()); case "AutoCAD": return(new AutoCADApp()); case "CorelDRAW": return(new CorelDRAWApp(vbe)); case "SolidWorks": return(new SolidWorksApp(vbe)); } } } } return(null); }
public static void ToWord() { Stopwatch watch = new Stopwatch(); watch.Start(); ed.WriteMessage("\n获取问题记录,请稍后..."); IMGLayers = GetIMGLayers(); // List<DBText> ents = GetLayerDbtxtByLayerName(IMGLayers); List <MText> txts = GetLayerDbtxtByLayerName(IMGLayers); if (txts.Count == 0) { watch.Stop(); ed.WriteMessage("\n未发现任何问题记录,请核对。"); } else { MSWord.Application WordApp; MSWord.Document WordDoc; CreatWordApp(out WordApp, out WordDoc); object format = MSWord.WdSaveFormat.wdFormatDocumentDefault; object filePath = Path.GetDirectoryName(acCurDb.Filename) + "\\" + Path.GetFileNameWithoutExtension(acCurDb.Filename) + "-问题记录.docx"; object endkeyunit = Microsoft.Office.Interop.Word.WdUnits.wdStory; object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine; object count = 1; List <string> txtcontent = (from txt in txts where txt != null select txt.Contents).ToList(); try { ed.WriteMessage("\n设置IMG-BIM问题记录模板.请稍后..."); SetPage(WordApp, WordDoc); AddPageHeaderFooter(WordApp, WordDoc); CreatFristTable(WordApp, WordDoc); ed.WriteMessage("\n模板创建完成,正在写入数据.请稍后..."); } catch (Exception) { ed.WriteMessage("\n创建Word过程发生错误,程序异常退出!"); } WordDoc.Tables[1].Cell(1, 2).Range.Text = "测试工程名"; ed.WriteMessage(txtcontent.Count.ToString()); for (int i = 1; i < txtcontent.Count / 3; i++) { WordDoc.Tables[1].Select(); WordApp.Selection.Copy(); WordApp.Selection.EndKey(ref endkeyunit, ref _nothing); //WordApp.Selection.MoveUp(ref unit, ref count, ref _nothing); object pBreak = (int)Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak; WordApp.Selection.InsertBreak(ref pBreak); WordApp.Selection.Paste(); } for (int i = 1; i < txtcontent.Count / 3 + 1; i++) { for (int j = i * 3 - 3; j < i * 3; j++) { WordDoc.Tables[i].Cell(2, 4).Range.Text = "叶舒帆"; switch (j % 3) { case 0: WordDoc.Tables[i].Cell(4, 2).Range.Text = txtcontent[j]; break; case 1: WordDoc.Tables[i].Cell(2, 10).Range.Text = txtcontent[j]; break; case 2: WordDoc.Tables[i].Cell(2, 6).Range.Text = txtcontent[j]; break; } } } WordDoc.SaveAs(ref filePath, ref format, 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); WordDoc.Close(ref _nothing, ref _nothing, ref _nothing); WordApp.Quit(ref _nothing, ref _nothing, ref _nothing); watch.Stop(); ed.WriteMessage("\n问题导出完成耗时:{0} ms,请到图纸目录下查看。", watch.ElapsedMilliseconds.ToString()); } }