csharp excel interop programming

zyip發表於2013-09-26

 

 

 string fileName = "c:\\a.xlsx";
            var application = new Application();
            application.Visible = true;
            var workbook = application.Workbooks.Open(fileName);
            var worksheet = workbook.Worksheets[2] as Microsoft.Office.Interop.Excel.Worksheet;
            //var worksheet = workbook.Worksheets.Add(Type.Missing,Type.Missing,Type.Missing,Type.Missing) as Microsoft.Office.Interop.Excel.Worksheet;

            worksheet.Cells[1,1] = "Hello World!";
            //Console.Read();

            worksheet.Range["A1"].Value = "Hello Range";

            worksheet.Range["A1:c3"].MergeCells=true;

            Range range = worksheet.Range["A1:A3"];
            range.Name = "range1";
            worksheet.Names.Add("range1", range);

            //worksheet.Range["range1"].Value;
            //worksheet.Range["t1!range1"].Value

            //enum range
            foreach (Microsoft.Office.Interop.Excel.Name name in worksheet.Names)
            {
                Console.WriteLine(name.RefersToRange.Cells.get_Address(true,true,Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1,Type.Missing));
                Console.WriteLine(name.RefersToRange.Cells.Worksheet.Name);
                Console.WriteLine(name.Name);
            }

            //search
            //set the cell color to red,which cell has the mached value
            Range currentFind = null;
            Range firstFind = null;
            Range Fruits = worksheet.get_Range("A1", "J50");
            currentFind = Fruits.Find("9300", Type.Missing,
                XlFindLookIn.xlValues, XlLookAt.xlPart,
                XlSearchOrder.xlByRows, XlSearchDirection.xlNext, false,
                Type.Missing, Type.Missing);
            while (currentFind != null)
            {
                // Keep track of the first range you find.  
                if (firstFind == null)
                {
                    firstFind = currentFind;
                }

                // If you didn't move to a new range, you are done. 
                else if (currentFind.get_Address(XlReferenceStyle.xlA1)
                      == firstFind.get_Address(XlReferenceStyle.xlA1))
                {
                    break;
                }

                currentFind.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
                currentFind.Font.Bold = true;

                currentFind = Fruits.FindNext(currentFind);
            }
            //end search

            application.Quit();

 

相關文章