예제 #1
0
        public static void WordToHtml(string sourceFileName, string targetFileName)
        {
            Microsoft.Office.Interop.Word.ApplicationClass WordApp;
            Microsoft.Office.Interop.Word.Document         WordDoc;
            Object oMissing = System.Reflection.Missing.Value;

            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            object fileName = sourceFileName;

            WordDoc = WordApp.Documents.Open(ref fileName,
                                             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            try
            {
                Type wordType = WordApp.GetType();
                // 打开文件
                Type docsType = WordApp.Documents.GetType();
                // 转换格式,另存为
                Type   docType      = WordDoc.GetType();
                object saveFileName = targetFileName;
                docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML });
            }
            finally
            {
                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
            }
        }
        /// <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;
            }
        }
예제 #3
0
        /// <summary>
        /// 获取word 无格式的text文本
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string WordToText(string path)
        {
            string wordText = "";

            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();//ApplicationClass();
            Microsoft.Office.Interop.Word.Document    WordDoc;
            Microsoft.Office.Interop.Word.Documents   docs = WordApp.Documents;

            Object oMissing = System.Reflection.Missing.Value;
            Type   wordType = WordApp.GetType();

            object fileName = path;

            WordDoc = WordApp.Documents.Open(ref fileName,
                                             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            wordText = WordDoc.Content.Text;

            WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
            WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
            GC.Collect();

            return(wordText);
        }
예제 #4
0
        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;
            }
        }
예제 #5
0
        public HardCopy(string workOrderNumber, string testCondition, string testPerformedOn)
        {
            WorkOrderNumber  = workOrderNumber;
            TestCondition    = testCondition;
            TestConditionAbr = testCondition == "As Received" ? "AR" : "TS";
            TestPerformedOn  = testPerformedOn;

            try
            {
                WordApp = new Word.Application();
                //WordApp.Visible = true;
                string path = testCondition == "As Received" ? @"hard_copy_location\Digital Datasheet Forms\AR_datasheet_template.docx" : @"hard_copy_location\Digital Datasheet Forms\TS_datasheet_template.docx";
                //string path = testCondition == "As Received" ? @"C:\Users\Nicholas\Documents\PTL\AR_datasheet_template.docx" : @"C:\Users\Nicholas\Documents\PTL\TS_datasheet_template.docx";
                WordDoc = WordApp.Documents.Open(path, true, true);
            }
            catch (Exception err)
            {
                sw = new StreamWriter(ErrorLogFilePath, true);
                sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nHardCopy constructor -- {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 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();
        }
        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 TestReport(string workOrderNumber, string testCondition, string partNumber, string dateCode, string testPerformedOn)
        {
            WorkOrderNumber  = workOrderNumber;
            TestCondition    = testCondition;
            TestConditionAbr = testCondition == "As Received" ? "AR" : "TS";
            PartNumber       = partNumber;
            DateCode         = dateCode;
            TestPerformedOn  = testPerformedOn;

            try
            {
                WordApp = new Word.Application();
                //WordApp.Visible = true;
                //var test = Word.Documents
                WordDoc = WordApp.Documents.Open(@"test_report_location\report_template.docx", true, true);
                WordDoc.Activate();
                // make a copy of the report template before entering in any data to use in case number of data rows exceeds limit for one page
                WordApp.ActiveDocument.Bookmarks[@"\Page"].Range.Copy();
                // create correct page break type to add when needed
                //object breakType = Word.WdBreakType.wdPageBreak;
            }
            catch (Exception err)
            {
                sw = new StreamWriter(ErrorLogFilePath, true);
                sw.WriteLine($"{DateTime.Now.ToShortTimeString()}\nReport constructor -- {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_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;
            }
        }
예제 #10
0
        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;
            }
        }
예제 #11
0
        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;
            }
        }
예제 #12
0
        /// <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;
            }
        }
        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 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_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 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;
            }
        }
예제 #18
0
        /// <summary>
        /// 表格处理
        /// </summary>
        /// <param name="filePath">word文件名</param>
        /// <returns></returns>
        public static bool AddTable(string filePath, System.Data.DataTable dt)
        {
            try
            {
                Object oMissing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word._Application WordApp = new Application();
                WordApp.Visible = true;
                object filename = filePath;
                Microsoft.Office.Interop.Word._Document WordDoc;
                if (File.Exists(filePath))
                {
                    WordDoc = WordApp.Documents.Open(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                     ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                }
                else
                {
                    WordDoc = WordApp.Documents.Add();
                }



                //插入表格
                Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref oMissing, ref oMissing);
                ////设置表格
                newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
                newTable.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                newTable.Columns[1].Width         = 100f;
                newTable.Columns[2].Width         = 220f;
                newTable.Columns[3].Width         = 105f;

                //填充表格内容
                newTable.Cell(1, 1).Range.Text = "我的简历";
                //设置单元格中字体为粗体
                newTable.Cell(1, 1).Range.Bold = 2;

                //合并单元格
                newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));

                //垂直居中
                WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                //水平居中
                WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                //填充表格内容
                newTable.Cell(2, 1).Range.Text = "座右铭:...";
                //设置单元格内字体颜色
                newTable.Cell(2, 1).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;
                //合并单元格
                newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
                WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                //填充表格内容
                newTable.Cell(3, 1).Range.Text = "姓名:";
                newTable.Cell(3, 2).Range.Text = "雷鑫";
                //纵向合并单元格
                newTable.Cell(3, 3).Select();
                //选中一行
                object moveUnit   = Microsoft.Office.Interop.Word.WdUnits.wdLine;
                object moveCount  = 3;
                object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
                WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
                WordApp.Selection.Cells.Merge();

                //表格中插入图片
                string pictureFileName  = System.IO.Directory.GetCurrentDirectory() + @"\picture.jpg";
                object LinkToFile       = false;
                object SaveWithDocument = true;
                object Anchor           = WordDoc.Application.Selection.Range;
                WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(pictureFileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
                //图片宽度
                WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;
                //图片高度
                WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;
                //将图片设置为四周环绕型
                Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
                s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;

                newTable.Cell(12, 1).Range.Text = "备注:";
                newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
                //在表格中增加行
                WordDoc.Content.Tables[1].Rows.Add(ref oMissing);

                //保存
                WordDoc.SaveAs2(filePath);
                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(false);
            }
        }
예제 #19
0
파일: Word.cs 프로젝트: yxx5006/CADAddin
        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());
            }
        }