Tuesday 12 June 2018

How to Create Excel File in Windows Form C#





using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Runtime.InteropServices;

using Excel = Microsoft.Office.Interop.Excel;



namespace WindowsFormsApplication7

{

    public partial class Form1 : Form

    {

        Excel.Application xlApp = new Excel.Application();

        public Form1()

        {

            InitializeComponent();

        }



        private void Form1_Load(object sender, EventArgs e)

        {

            if (xlApp == null)

            {

                label1.Text = "Excel Libary is not installed ";

                label1.ForeColor = System.Drawing.Color.Red;

            }

            else

            {

                label1.Text = "Excel Libary is  installed ";

                label1.ForeColor = System.Drawing.Color.Green;

         

            }

        }



        private void button1_Click(object sender, EventArgs e)

        {

            Excel.Workbook xlWorkBook;

            Excel.Worksheet xlWorkSheet;

            object misValue = System.Reflection.Missing.Value;



            xlWorkBook = xlApp.Workbooks.Add(misValue);

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);



            xlWorkSheet.Cells[1, 1] = "StudentID";

            xlWorkSheet.Cells[1, 2] = "Student Name";

            xlWorkSheet.Cells[1, 3] = "Marks";



            xlWorkSheet.Cells[2, 1] = "1";

            xlWorkSheet.Cells[2, 2] = "Ali";

            xlWorkSheet.Cells[2, 3] = "50";



            xlWorkSheet.Cells[3, 1] = "2";

            xlWorkSheet.Cells[3, 2] = "Salman";

            xlWorkSheet.Cells[3, 3] = "60";





            xlWorkSheet.Cells[4, 1] = "3";

            xlWorkSheet.Cells[4, 2] = "Arsalan";

            xlWorkSheet.Cells[4, 3] = "100";







            xlWorkBook.SaveAs(@"C:\images\docs\salman.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

            xlWorkBook.Close(true, misValue, misValue);

            xlApp.Quit();



            Marshal.ReleaseComObject(xlWorkSheet);

            Marshal.ReleaseComObject(xlWorkBook);

            Marshal.ReleaseComObject(xlApp);



            MessageBox.Show("Excel file created , you can find the file d:\\csharp-Excel.xls");

        }



    }

}


Pass Dynamically Added Html Table Records List To Controller In Asp.net MVC

Controller Code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ...