Suppose you have an Excel File
SampleFile.xls which has 1 column with the heading
Age and below that there are certain values and you have to read the last value of that column into a textbox then you can follow the below mentioned steps:
1. First Add a Label and Textbox on your aspx page. This is the textbox in which the Excel file value will be displayed.
<asp:label id="Label1" runat="server" text="Age" ></asp:label>
<asp:textbox id="TextBox1" runat="server"></asp:textbox>
2. In the code behind file write the following code to get the value in a textbox from excel file.
Microsoft.Office.Interop.Excel.Application _excelApp = new Microsoft.Office.Interop.Excel.Application();
_excelApp.Visible = true;
string fileName = "C:\\Users\\kritijain\\Desktop\\SampleFile.xls";
Workbook workbook = _excelApp.Workbooks.Open(fileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
Range excelRange = worksheet.UsedRange;
object[,] valueArray = (object[,])excelRange.get_Value(
XlRangeValueDataType.xlRangeValueDefault);
for (int row = 1; row <= worksheet.UsedRange.Rows.Count; ++row)
{
for (int col = 1; col <= worksheet.UsedRange.Columns.Count; ++col)
{
Debug.Print(valueArray[row, col].ToString());
TextBox1.Text = valueArray[row, col].ToString();
}
}
workbook.Close(false, Type.Missing, Type.Missing);
Marshal.ReleaseComObject(workbook);
_excelApp.Quit();
Marshal.FinalReleaseComObject(_excelApp);
3. Add the following reference
Right click on your project and go to Add reference. Add the Microsoft.Office.Interop.Excel assembly.
Include using Microsoft.Office.Interop.Excel; to make use of assembly.