상세 컨텐츠

본문 제목

MS WORD EXCEL 파일 문자열 대체하기 VS2010 C#

C#

by xarfox 2014. 10. 15. 09:56

본문





참조 추가

=====================================

using Microsoft.Office.Core;

using Microsoft.Office.Interop;

//using Excel;

using System.Reflection;

using Excel = Microsoft.Office.Interop.Excel;

using Word = Microsoft.Office.Interop.Word;

using System.Runtime.InteropServices;

=====================================


==================워드 코드 내용========================


        private void button3_Click(object sender, EventArgs e)

        {

            

            OpenFileDialog ofd = new OpenFileDialog();

            if (DialogResult.OK == ofd.ShowDialog(this))

            {

                object fname = ofd.FileName;

                CreateWordDocument(fname, @"c:\test.doc");

            }

        }


        private void CreateWordDocument(object fileName, object saveAs)

        {

            //참조 추가 COM, Office.Core, Office.Interop.Word

            //using Microsoft.Office.Core;

            //using Microsoft.Office.Interop;

            //using Word = Microsoft.Office.Interop.Word;


            // Set Missing Value parameter - used to represent

            // a missing value when calling methods through

            // interop


            object missing = System.Reflection.Missing.Value;


            //setup the word.Application class.

            Word.Application wordApp = new Word.ApplicationClass();


            //setup our Word.Document calss we'll use/

            Word.Document aDoc = null;


            //check to see that file exists


            if (File.Exists((string)fileName))

            {

                DateTime today = DateTime.Now;


                object readOnly = false;

                object isVisible = false;



                //Open the word document

                aDoc = wordApp.Documents.Open(ref fileName, ref missing,

                    ref readOnly, ref missing, ref missing, ref missing,

                    ref missing, ref missing, ref missing, ref missing,

                    ref missing, ref isVisible, ref missing, ref missing,

                    ref missing, ref missing);

                

                //activate the document

                aDoc.Activate();


                // find Place Holders and REplace them with Values.


                this.FindAndReplace(wordApp, "<a>", "name of article");

                this.FindAndReplace(wordApp, "<b>", "nomenclature");

                this.FindAndReplace(wordApp, "<c>", "job id");

                this.FindAndReplace(wordApp, "<d>", "engineering dep.");

                this.FindAndReplace(wordApp, "<_C>", "0.005");

                this.FindAndReplace(wordApp, "<_Si>", "9.99");


                //Example of writing to the start of a document.

                aDoc.Content.InsertBefore("this is at the beginning\r\n\r\n");


                //Example of writing to the end of a document.

                aDoc.Content.InsertAfter("\r\n\r\nThis is at the end");

            }

            else

            {

                MessageBox.Show("File dose ont exist.");

                return;

            }


            //Save the document as the correct file name.

            aDoc.SaveAs(ref saveAs, ref missing, ref missing, ref missing,

                ref missing,  ref missing, ref missing, ref missing,

                ref missing,  ref missing, ref missing, ref missing,

                ref missing,  ref missing, ref missing, ref missing);

            

            aDoc.Close(ref missing, ref missing, ref missing);

            


            Process[] msWord = Process.GetProcessesByName("WINWORD");

            if (msWord.Count() != 0)

            {

                msWord[0].Kill();

            }


            MessageBox.Show("File created");



            }



        private void FindAndReplace(Word.Application WordApp, object findText, object replaceWithText)

        {

            object matchCase = true;

            object matchWholeWord = true;

            object matchWildCards = false;

            object matchSoundsLike = false;

            object matchAllWordForms = false;

            object forward = true;

            object format = false;

            object matchKashida = false;

            object matchDiacritics = false;

            object matchAlefHamza = false;

            object matchControl = false;

            object read_only = false;

            object visible = false;

            object replace = 2;

            object wrap = 1;


            WordApp.Selection.Find.Execute(ref findText,

                ref matchCase, ref matchWholeWord,

                ref matchWildCards, ref matchSoundsLike,

                ref matchAllWordForms, ref forward,

                ref wrap, ref format, ref replaceWithText,

                ref replace, ref matchKashida,

                ref matchDiacritics, ref matchAlefHamza,

                ref matchControl);

        }

====================엑셀=========================================

        private void btn_excel_replace_Click(object sender, EventArgs e)
        {

            object m = Type.Missing;

            Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application();
                

            //xlapp.FindFormat.Font.Name = "Arial";

            Excel.Workbook wb = default(Microsoft.Office.Interop.Excel.Workbook);

            wb = xlapp.Workbooks.Open(@"C:\DevProgram\SUNGHO_METAL_CHEMICAL\KMC_REPORT.xls",
                m, false, m, m, m, m, m, m, m, m, m, m, m, m);

            wb.Worksheets.Application.Cells.Replace((object)tbx_excel_src.Text.Trim(), (object)tbx_excel_dest.Text.Trim(), Excel.XlLookAt.xlWhole, Excel.XlSearchOrder.xlByRows, false, m, m, m);

            wb.SaveAs(@"C:\excel_replaced.xls", m, m, m, m, m, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, m, m, m, m, m);
            
            xlapp.Quit();
            xlapp = null;
        }
        
        static void ReplaceTextInExcelFile(string filename, string replace, string replacement)
        {
            object m = Type.Missing;

            // open excel.
            Excel.Application app = new Microsoft.Office.Interop.Excel.Application();

            // open the workbook. 
            Excel.Workbook wb = app.Workbooks.Open(
                filename,
                m, false, m, m, m, m, m, m, m, m, m, m, m, m);

            // get the active worksheet. (Replace this if you need to.) 
            Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;

            // get the used range. 
            Excel.Range r = (Excel.Range)ws.UsedRange;

            // call the replace method to replace instances. 
            bool success = (bool)r.Replace(
                replace,
                replacement,
                Excel.XlLookAt.xlWhole,
                Excel.XlSearchOrder.xlByRows,
                true, m, m, m);

            // save and close. 
            wb.Save();
            app.Quit();
            app = null;
        }
        


관련글 더보기