|
|
|
|
|
Home
»
Windows Forms
»
How To Open and Read an Excel Spreadsheet into a ListView in .NET
|
How To Open and Read an Excel Spreadsheet into a ListView in .NET
By
Mike Gold November 26, 2001
The Interoperability services make it very easy to work with COM Capable Applications such as Word and Excel.
|
Author Rank:
|
|
Technologies:
Windows Forms,Visual C# .NET |
|
Total downloads : |
4086 |
|
Total page views : |
338207 |
|
Rating : |
|
4.2/5 |
|
This article has been rated : |
5 times |
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
Related EbooksTop Videos
|
|
|
Description
|
|
The Complete Visual C# Programmer's Guide, written by the authors of C# Corner, covers most of the major components that make up C# and the .NETenvironment including Windows Forms, ADO.NET, GDI+, Web Services, and Security. The book is geared toward the beginner to intermediate programmers.
|
|
|
|
|
|
|
|
|
|
|
|
|
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?

Figure 1 - Excel Spreadsheet read into a ListView
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:
private Excel.Application ExcelObj = null;
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:
public Form1() { // Initialize the Windows Components InitializeComponent(); ExcelObj = new Excel.Application(); // See if the Excel Application Object was successfully constructed if (ExcelObj == null) { MessageBox.Show("ERROR: EXCEL couldn't be started!"); System.Windows.Forms.Application.Exit(); } // Make the Application Visible ExcelObj.Visible = true; }
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.
private void menuItem2_Click(object sender, System.EventArgs e) { // prepare open file dialog to only search for excel files (had trouble setting this in design view) this.openFileDialog1.FileName = "*.xls";if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { // Here is the call to Open a Workbook in Excel // It uses most of the default values (except for the read-only which we set to true) Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open( openFileDialog1.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,0, true); // get the collection of sheets in the workbook Excel.Sheets sheets = theWorkbook.Worksheets; // get the first and only worksheet from the collection of worksheets Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); // loop through 10 rows of the spreadsheet and place each row in the list view for (int i = 1; i <= 10; i++) { Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString()); System.Array myvalues = (System.Array)range.Cells.Value; string[] strArray = ConvertToStringArray(myvalues); listView1.Items.Add(new ListViewItem(strArray)); } } }
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.
string[] ConvertToStringArray(System.Array values) { // create a new string array string[] theArray = new string[values.Length]; // loop through the 2-D System.Array and populate the 1-D String Array for (int i = 1; i <= values.Length; i++) { if (values.GetValue(1, i) == null) theArray[i-1] = ""; else theArray[i-1] = (string)values.GetValue(1, i).ToString(); } return theArray; }
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).
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
|
|
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
|
|
|
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| |
| |