참조 : http://www.c-sharpcorner.com
How to Open and Read an Excel Spreadsheet into a ListView in .NET |
Submitted By | User Level | Date of Submission |
Michael Gold | Intermediate | 11/26/2001 |
Figure 1 - Excel Spreadsheet read into a ListView Source Code: ExcelReadMG.zip The Interoperability services make it very easy to work with COM Capable Applications such as Word and Excel. You can also refer to my previous article on the topic: Real-time Stock Quotes in Excel using .NET for more information on accessing Excel via .NET. This article was written in response to a question asking How do I open and excel file and read it using .NET? The first step is to create a reference in your project to Excel 9.0 Objects Library. This is done by right mouse clicking on the References folder in the Solution Explorer and choosing Add Reference. This brings up the Tab Dialog below. Choose the COM Tab and pick Microsoft Excel 9.0 Objects Library.
Figure 2 - Adding an Excel Reference This action puts an Interop.Excel.dll and Interop.Office.dll into your bin directory so you can manipulate excel. Now we can declare our Excel Application Object and the compiler will recognize it:
Excel is launched and an Application reference is obtained in the constructor of our form. First an Excel Application object is constructed. Then we check to make sure Excel was actually started. If it was, we have a valid application object and we can now use it to open a file:
The code for opening the Excel file is shown below. The code uses the OpenFileDialog component to get the path name for the Excel file. The Excel file is opened using the WorkBooks collections' Open method. This method takes 15 parameters with the following definition. Function Open(Filename As String, [UpdateLinks], [ReadOnly], [Format], [Password], [WriteResPassword], [IgnoreReadOnlyRecommended], [Origin], [Delimiter], [Editable], [Notify], [Converter], [AddToMenuRecentlyUsed]) As Workbook We really are only interested in the FileName, but have added the other default parameters for your reference. There is also an OpenText method in Workbooks for opening tab or comma delimited text files.
You also may want to note the ConvertToStringArray method which is used to convert a System.Array into a string array. If someone knows an easier way to do this, please let me know and I'll alter the article. The problem is that an Excel Array comes back as two dimensional even if you are selecting a range of a single row, so you need to change the 2-d array into something the listview can accept. Also the listview array is 0 based and the Excel range array is 1 based.
That's all there is to it! Now you can read in all your old Excel Databases. Perhaps you can even use ADO.NET to place them into a database! (Could be the topic for the next article. ;-) |
'programming > c#' 카테고리의 다른 글
엑셀 파일에서 데이터를 load할 때... (0) | 2003.10.30 |
---|---|
엑셀 파일 생성 코드 (0) | 2003.10.30 |
프로젝트 배포 (0) | 2003.10.20 |