how to read information inside an excel sheet using C# code......
-
this is an exact duplicate question. Somebody add the dupe links and close.Anonymous Type– Anonymous Type2011-01-04 21:09:16 +00:00Commented Jan 4, 2011 at 21:09
-
possible duplicate of Reading Excel files from C#Doc Brown– Doc Brown2011-01-04 21:34:33 +00:00Commented Jan 4, 2011 at 21:34
6 Answers
You can either use Oledb
using System.Data;
using System.Data.OleDb;
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties=Excel 8.0");
OleDbDataAdapter da = new OleDbDataAdapter("select * from MyObject", con);
DataTable dt = new DataTable();
da.Fill(dt);
or you use Office Interop
this.openFileDialog1.FileName = "*.xls";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
openFileDialog1.FileName, 0, true, 5,
"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
0, true);
Excel.Sheets sheets = theWorkbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
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);
}
}
2 Comments
If the data is tabular, use OleDB, otherwise you can use Automation to automate Excel and copy the values over to your app.
Or if it's the new XML format excel sheets you might be able to do it via the framework classes.
Info about Excel Automation: How to: Use COM Interop to Create an Excel Spreadsheet
Info about Excel via OleDB: How To Use ADO.NET to Retrieve and Modify Records in an Excel Workbook With Visual Basic .NET
1 Comment
NPOI is the way to go.
Using office interop requires that Office (and the right version) be installed on the machine your app is running on. If a web abb, that probably means no, and it's not robust enough for a production environment anyway. OLEDB has serious limitations, unless it's a one-off and the data is really simple I wouldn't use it.
3 Comments
- Excel COM Interop - via Microsoft.Office.Interop.Excel + Microsoft.Office.Interop.Excel.Extensions
- ADO.Net via OLEDB data provider for Excel.
- Use of System.XML and/or Linq to XML and/or Open XML SDK (can also be used to create new books programmatically from scratch).
- 3rd party library such as NPOI.
- 3rd party vendor package such as spreadsheetgear