Click here to Skip to main content
15,040,212 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
how to display an excel cell value into a text box
Posted
Comments
[no name] 14-Nov-13 2:24am
   
check this dhaval

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.

C#
<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.

C#
//create the Application object we can use in the member functions.
       Microsoft.Office.Interop.Excel.Application _excelApp = new Microsoft.Office.Interop.Excel.Application();
       _excelApp.Visible = true;

       string fileName = "C:\\Users\\kritijain\\Desktop\\SampleFile.xls";

       //open the workbook
       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);

       //select the first sheet
       Worksheet worksheet = (Worksheet)workbook.Worksheets[1];

       //find the used range in worksheet
       Range excelRange = worksheet.UsedRange;

       //get an object array of all of the cells in the worksheet (their values)
       object[,] valueArray = (object[,])excelRange.get_Value(
                   XlRangeValueDataType.xlRangeValueDefault);

       //access the cells
       for (int row = 1; row <= worksheet.UsedRange.Rows.Count; ++row)
       {
           for (int col = 1; col <= worksheet.UsedRange.Columns.Count; ++col)
           {
               //access each cell
               Debug.Print(valueArray[row, col].ToString());
               TextBox1.Text = valueArray[row, col].ToString();
           }
       }

       //clean up stuffs
       workbook.Close(false, Type.Missing, Type.Missing);
       Marshal.ReleaseComObject(workbook);

       _excelApp.Quit();
       Marshal.FinalReleaseComObject(_excelApp);


3. Add the following reference
SQL
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.
   
v3
Comments
kevinviji 10-Mar-14 3:10am
   
This code works fine if a sheet contain data in every cell.otherwise null reference error thrown

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900