Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
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

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
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ExcelReadMG.zip
 
ArticleAd
Become a Sponsor



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
 [Top] Rate this article
 About the author
 
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
Looking for C# Consulting?
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.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ExcelReadMG.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
How to delete a row from an Excel sheet using C#.netPrabhu8/4/2006
How to delete first Row from an Excel sheet using C#.net. For my project its very important. I am New for DotNet. So i don't know what to do. Please Help. Please mail me: prabhubn@officetiger.com
Reply | Email | Delete | Modify | 
Question : getting exception in opened excel filevivek1/30/2007
hi, i opened excel file in my c# application in readonly mode with open(.......) method and visible = false; and after that if open same excel file seperately in window my application throws exception
Reply | Email | Delete | Modify | 
Import Excel Data into SQL server2000 DatabaseAmita2/27/2007
This artical is very helpful to me to develope an web- application .net which is related to upload a excel file but now i want to store it's contents in SQL server2000 database which create tables dynamically , thanks for ur help
Reply | Email | Delete | Modify | 
 
 
Re: Import Excel Data into SQL server2000 DatabaseSangDV10/3/2007
#region Hàm Insert vào CSDL (chua thành công) private void button4_Click(object sender, EventArgs e) { { if (dt != null) // dt là 1 DataTable dùng d? hi?n th? ra DataGrid { int numrows = dt.Rows.Count; // s? dòng trong DataTable for (int i = 0; i < numrows; i++) { try { #region Ð?y d? li?u vào Paramater SqlParameter[] prm = new SqlParameter[5]; prm[0] = new SqlParameter("@Num1", SqlDbType.NVarChar); prm[0].Value = dt.Rows[i][0].ToString(); prm[1] = new SqlParameter("@Num2", SqlDbType.NVarChar); prm[1].Value = dt.Rows[i][1].ToString(); prm[2] = new SqlParameter("@Num3", SqlDbType.NVarChar); prm[2].Value = dt.Rows[i][2].ToString(); prm[3] = new SqlParameter("@Num4", SqlDbType.NVarChar); prm[3].Value = dt.Rows[i][3].ToString(); prm[4] = new SqlParameter("@Num5", SqlDbType.NVarChar); prm[4].Value = dt.Rows[i][4].ToString(); string strSql = "SP_Test"; DataSet ds = Util.GetDataSet(strSql, prm); #endregion } catch { MessageBox.Show("Không thành công!"); } } } MessageBox.Show("Thành công!"); } } #endregion
Reply | Email | Delete | Modify | 
 
Re: Re: Import Excel Data into SQL server2000 Databaseravi8/27/2008

Hi i want to read data from excel file ,using C#.net 2005 and storing it in sql server 2005.

i cant use sqlbulkcopy as my excel file is not formatted.

i have to read cell by cell..

and store it in database.

please do provide some code

Thanks

Sakee

Reply | Email | Delete | Modify | 
 
Re: Re: Import Excel Data into SQL server2000 Databaseravi8/27/2008

Hi ,i want to read excel file from c# and then store it into sql server 2005.

i cant use bulkcopy as excel file is not formated.

i have to read cell by cell .

please gice some code and and i am new to c#..

Thanks

Sakeee

Reply | Email | Delete | Modify | 
Interop.Office.dll not found in bin directoryJacobs4/19/2007
The Interop.Office.dll is not stored in my bin directory. And my code to generate an Excel is also not working. What did i forgot to do/install? Can anaybody help me please?? Thx!
Reply | Email | Delete | Modify | 
 
 
Re: Interop.Office.dll not found in bin directoryMahesh4/19/2007
Do you have office installed on your machine? Have you added reference to Excel 9.0 Lib?
Reply | Email | Delete | Modify | 
 
Re: Re: Interop.Office.dll not found in bin directoryFilip3/19/2008
That is the problem - you have to have installed office.Using Excel Automation has many disadvantages, so I think it is better not to use it. Just look why is our .NET component better than Excel Automation. We have a free version of this C#/VB.NET component that you can use in your application (even in commercial ones).
Reply | Email | Delete | Modify | 
Excel.Application is not detected .. manu5/22/2007
Excel.Application is not detected . i am getting error Error 1 The type or namespace name 'Excel' could not be found . i have installed excel 2003 , i have selected MS excel 11.0 in the COM tab
Reply | Email | Delete | Modify | 
 
 
Re: Excel.Application is not detected .. arghad5/22/2007
Ok .. here is a working version from the code:
using ExcelInterop = Microsoft.Office.Interop.Excel;

ExcelInterop.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelInterop.WorkbookClass workBook = (ExcelInterop.WorkbookClass)excel.Workbooks.Open(Path, 0, true, 5, "", "", true, ExcelInterop.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
ExcelInterop.Sheets sheets = workBook.Worksheets;
ExcelInterop.Worksheet worksheet = (ExcelInterop.Worksheet)sheets.get_Item(1);
ExcelInterop.Range range = worksheet.get_Range("A1", "A300");
System.Array myvalues = (System.Array)range.Cells.Value2;
string[] strArray = ConvertToStringArray(myvalues);
for (int i = 1; i < strArray.Length; i++)
{
Console.WriteLine(strArray[i]);
}

and of course the method:
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(i, 1) == null) continue;
theArray[i-1] = (string)values.GetValue(i, 1).ToString();
}
return theArray;
}
Hope this help ;-)
Arghad
Reply | Email | Delete | Modify | 
 
It's reading the First Column only......What i do further to read N number of ColumnVictor6/16/2007

 

Hai...

         Its working Fine.But it should read the First column values only.if I change A1 object and A300 object to 'C' or 'D' it reads the 3 0r 4 th column respectivily.Why it is so...Pls give the soln to read the Excel file full column.

Thnx.

Victor

 

 

Reply | Email | Delete | Modify | 
 
Re: Excel.Application is not detected .. Danny Garduce10/10/2007

Try to include this on the top of your code

using Microsoft.Office;

Reply | Email |