In this post we will tell you how to create a excel file using c#
There are a few step that should follow to create excel file.
Step 1. Open visual stdio and open Window Form Application.
Stpep2 . Add reference to Micosoft Excel 12.0 object library. (Read more)
Now make a form as show below:
Step 3. Double click save button and code view will be open as shown below.
Step 4. Add reference to “Microsoft.Office.Interop.Excel” shown as:-
using Excel=Microsoft.Office.Interop.Excel;
Step 5. Now create a Method named “releaseObject” shown as:-
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
Step 6. Go to Design view and double click save Button and paste the coding given below:-
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "Name";
xlWorkSheet.Cells[1, 2] = "Father name";
xlWorkSheet.Cells[1, 3] = "Date";
xlWorkSheet.Cells[1, 4] = "phone";
xlWorkSheet.Cells[1, 5] = "Address";
xlWorkSheet.Cells[2, 1] = textBox1.Text;
xlWorkSheet.Cells[2, 2] = textBox2.Text;
xlWorkSheet.Cells[2, 3] = textBox3.Text;
xlWorkSheet.Cells[2, 4] = textBox4.Text;
xlWorkSheet.Cells[2, 5] = textBox5.Text;
xlWorkSheet.Columns.AutoFit();
xlWorkBook.SaveAs("create-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , See it in My Document");
Step 7. Run project , give values and click save, your file will be saved.
Thanks for Reading..
Enjoy..
Thanks for Reading..
Enjoy..
Post a Comment