반응형

C#으로 엑셀 데이터를 다뤄보자.

 

Microsoft Excel XX.X Object Library를 추가한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Excel.Application application = new Excel.Application();
            application.Visible = false;
            Excel.Workbook workbook = application.Workbooks.Open(@"d:\test.xlsx");
 
            Console.WriteLine("Number of sheets: " + workbook.Worksheets.Count);
 
            Console.WriteLine();
 
            Excel.Worksheet worksheet1 = workbook.Worksheets.Item[1];
            Excel.Worksheet worksheet2 = workbook.Worksheets.Item[2];
            Excel.Worksheet worksheet3 = workbook.Worksheets.Item[3];
 
            Console.WriteLine("Name of 1st sheet: " + worksheet1.Name);
            Console.WriteLine("Name of 2nd sheet: " + worksheet2.Name);
            Console.WriteLine("Name of 3rd sheet: " + worksheet3.Name);
 
            Console.WriteLine();
 
            //Excel.Range cell1 = worksheet1.Range["C2"];
            Excel.Range cell1 = worksheet1.Cells[23];
            Console.WriteLine("1st sheet [2, 3]: " + cell1.Value);
 
            Console.WriteLine();
 
            Console.WriteLine("2nd sheet [3, 1]: " + worksheet2.Cells[31].Value);
 
            Console.WriteLine();
 
            //Excel.Range range = worksheet2.Range["A1:C3"];
            Excel.Range range = worksheet2.Range[worksheet2.Cells[11], worksheet2.Cells[33]];
            for (int i = 1; i < 4; i++)
                for (int j = 1; j < 4; j++)
                {
                    Console.WriteLine("2nd sheet [{0}, {1}]: {2}", i, j, range.Cells[i, j].Value);
                }
 
            Console.WriteLine();
 
            //Excel.Range find = worksheet2.Range["A1:C3"].Find("vwx", Type.Missing, Excel.XlFindLookIn.xlValues,
            //    Excel.XlLookAt.xlWhole, Excel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlNext, false);
            Excel.Range find = worksheet2.Range["A1:C3"].Find("vwx");
            Console.WriteLine($"{find.Address} [{find.Row}, {find.Column}]: {worksheet2.Range[find.Address].Value}");
 
            workbook.Close();
            application.Quit();
 
            Marshal.ReleaseComObject(worksheet1);
            Marshal.ReleaseComObject(worksheet2);
            Marshal.ReleaseComObject(worksheet3);
 
            Marshal.ReleaseComObject(workbook);
 
            Marshal.ReleaseComObject(application);
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

 

Sheet1

 

Sheet2

 

Sheet3

 

text.xlsx 의 정보가 표시된다.

 

반응형
Posted by J-sean
: