Read Excel file with Excel object
==================================
using Microsoft.Office.Interop.Excel;
private Excel.Application ExcelObj = null;
// Create Object with File path
Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open((Server.MapPath(“..//Data”) + “\\”
+ fu.FileName), 0, true, 5, “”, “”, true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, “\t”, false, false, 0, true, true, true);
// get the collection of sheets in the workbook
Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
// get the first and only worksheet from the collection of worksheets
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
// Loop through total row count
for (int i = 0; i < worksheet.Rows.Count; i++)
{
// Get value from ranges.
Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range(“A” + i.ToString(), “B” + i.ToString());
// In Array, You will get the cell value
System.Array myvalues = (System.Array)range.Cells.Value2;
// By Row, Column
string Value1 = myvalues.GetValue(1, 1) != null ? myvalues.GetValue(1, 1).ToString() : string.Empty;
string Value2 = myvalues.GetValue(1, 2) != null ? myvalues.GetValue(1, 2).ToString() : string.Empty;
}
Read Excel File with out Excel Object
=====================================
string strConn;
strConn = “Provider=Microsoft.Jet.OLEDB.4.0;” +
“Data Source=” + Server.MapPath(“”) + “;” +
“Extended Properties=Excel 8.0;”;
OleDbConnection con = new OleDbConnection(strConn);
con.Open();
if (con.State == ConnectionState.Open)
{
OleDbDataAdapter adp = new OleDbDataAdapter(“Select * From [test$A1:D65536]“, con);
DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);
}
con.Close()
Filed under: Excel
Beware of COM automation drawbacks.
If you have small workbooks you can use GemBox.Spreadsheet Free
Excel component for XLS/CSV/XLSX reading/writing/reporting.
I read your posts for a long time and should tell that your articles always prove to be of a high value and quality for readers.
Hi.. Liza,
Thanks very much for your complements.
In “OleDbDataAdapter adp = new OleDbDataAdapter(”Select * From [test$A1:D65536]“, con);” I don’t known [test$A1:D65536], please guide me
Hi Sang,
[ test$A1:D65536]“, ]
This means, you are accessing excel file with Sheet name ‘Test’ and its ranges from A1 to D65536 [Here, 65636 means all the cells of column D means till the last cell of excel file in Column C]
Regards,
Abhi
Hi abhim,
I have been successful in reading all the sheets in an excel book. But after I read the excel, it becomes locked. So I can only open it in the read only mode.
I have googled. But very thin voices heared over there. Any idea would be much useful.
With appreciation. Thanks.