Step 1: - Open Visual Studio 2015
=> Goto File Menu => New => Project...
Step 2: - In the Installed
Templates list, select Visual C# => Windows
Step 3: - Select Console
Application from the Windows list => Type ExportToExcel in
the Name box and click OK
Step 4:- Right Click
on References => Click on Add References… => Expand COM
link from left pane => Select Type Libraries => Checked Microsoft Excel 12.0 Object
Library check box from middle pane => Click OK
Step 5:- Copy Past Code in Program.cs
using System;
using System.Data;
using System.Reflection;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExportToExcel
{
class Program
{
protected static
DataTable
GeTable()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dt.Columns.Add(new DataColumn("Column4", typeof(string)));
int totalRow = 10;
for (int
i = 0; i < totalRow; i++)
{
dr = dt.NewRow();
dr["Column1"] = "Row" + i;
dr["Column2"] = "Row" + i;
dr["Column3"] = "Row" + i;
dr["Column4"] =
1000 / (i + 1);
dt.Rows.Add(dr);
}
return dt;
}
static void
Main(string[]
args)
{
try
{
Excel.Application
objExcelApplication;
Excel.Workbook
objExcelWorkbook;
Excel.Worksheet
objExcelWorksheet;
object misValue = Missing.Value;
objExcelApplication = new Excel.Application();
objExcelWorkbook =
objExcelApplication.Workbooks.Add(misValue);
objExcelWorksheet = (Excel.Worksheet)objExcelWorkbook.Worksheets.get_Item(1);
//Get
Data
DataTable dataTable = GeTable();
if (dataTable != null)
{
if (dataTable.Rows.Count > 0)
{
int colCount = dataTable.Columns.Count;
int rowCount = dataTable.Rows.Count;
// Write Excel Column
for (int i = 0; i < colCount; i++)
{
objExcelWorksheet.Cells[1, (i + 1)] =
dataTable.Columns[i].ToString();
}
// Write Excel Rows
for (int i = 0; i < rowCount; i++)
{
for (int
j = 0; j < colCount; j++)
{
objExcelWorksheet.Cells[(i + 2), (j + 1)] = dataTable.Rows[i][j];
}
}
}
}
string fileName = string.Format("{0}{1}.{2}", "ExcelRpt", DateTime.Now.ToString("ddMMyyyy
hh_mm_ss tt"), "xls");
string savePath = AppDomain.CurrentDomain.BaseDirectory + fileName;
objExcelWorkbook.SaveAs(savePath,
Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue,
misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue,
misValue);
objExcelWorkbook.Close(true, misValue, misValue);
objExcelApplication.Quit();
Marshal.ReleaseComObject(objExcelWorksheet);
Marshal.ReleaseComObject(objExcelWorkbook);
Marshal.ReleaseComObject(objExcelApplication);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Output
Note:
- Excel file will be creating inside the project bin\Debug folder.
No comments:
Post a Comment