Reputation: 269
I am aware that we can read excel .xls
file using following way
We can use FileStream
to read flat files, is not there any way to read .xls
file using inbuilt class library in .NET Framework
?
Upvotes: 5
Views: 18493
Reputation: 20342
Here is a simple example to get you going.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
Excel.Range range ;
string str;
int rCnt ;
int cCnt ;
int rw = 0;
int cl = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(@"d:\csharp-Excel.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
rw = range.Rows.Count;
cl = range.Columns.Count;
for (rCnt = 1; rCnt < = rw; rCnt++)
{
for (cCnt = 1; cCnt < = cl; cCnt++)
{
str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
MessageBox.Show(str);
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
}
}
}
http://csharp.net-informations.com/excel/csharp-read-excel.htm
Remember to add a reference to Microsoft Excel 15.0 Object Library
Upvotes: 4
Reputation: 26926
If you can add the Microsoft Open XML 2 SDK to your application, you can read the modern Open XML file formats and then parse the XML files for the Excel data.
If you can't use Microsoft's solution, you would have to write your own, using the Open XML file format as your guide.
Upvotes: 0
Reputation: 6637
The most fair way to read xls from c# is to use Microsoft Primary interop assemblies (PIA) for Excel (that's "Interop" from your options). However there is a big disadvantage that it needs to have Microsoft Excel installed on computer running this code. These libraries are some kind of wrappers above Excel application, but it should allow you to read everything that can be available from Excel object model.
From my experience this way is more or less good for desktop applications, but it is not good for server-side Excel file processing.
Upvotes: 1