Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have exported values from datatable to excel using list.. I have inserted values to the list and passed that in a grid and using ExporttoExcel() i have exported it to excel..
here is the code for list...
C#
protected void Page_Load(object sender, EventArgs e)
        {
            List<student> Students = new List<student>(){
                new Student() { Name = "Jack", Age = 15, StudentId = 100 },
                new Student() { Name = "Smith", Age = 15, StudentId =101 },           
                new Student() { Name = "Smit", Age = 15, StudentId = 102 },
                new Student() { Name = "Anusha", Age = 23, StudentId = 104 }
            };
            ListtoDataTableConverter converter = new ListtoDataTableConverter();
            dt = converter.ToDataTable(Students);
            GridView_Result.DataSource = Students;
            GridView_Result.DataBind();
        }

now, i want to insert values from front end and i want that to be saved in excel.. instead of using grid, i will use a text field and after entering value and if u click insert button, it should be saved in excel sheet...is there any ways to do so ...

thanks a ton..!!
Posted
Updated 9-Sep-12 19:11pm
v2

1 solution

check this code

C#
//namespace for excel
using excel = Microsoft.Office.Interop.Excel;



	    excel.Application eApp = new excel.Application();
            excel.Worksheet eWs = new excel.Worksheet();
            excel.Workbook eWs1;
            eWs1 = (excel.Workbook)(eApp.Workbooks.Add([Excel Path]));
            eWs = (excel.Worksheet)eWs1.Worksheets[0];
            eApp.Visible = true;

	    DataTable dt = new DataTable();

            //fill data table here
            //make current sheet active

            eWs.Select(Type.Missing);

		int iRow = 1;
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    
                    
                    eWs.Cells[iRow, 1] = Convert.ToString(dr["column1"]);
                    eWs.Cells[iRow, 2] = Convert.ToString(dr["column2"]);
                    eWs.Cells[iRow, 3] = Convert.ToString(dr["column3"]);
                    eWs.Cells[iRow, 4] = Convert.ToString(dr["column4"]);
                     iRow++;
                 }
             }
//save the workbook

eWs1.SaveAs([Excel Path], Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
 
Share this answer
 

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