Export SQL to Excel

Your best bet might be to just write it out to a CSV. Excel registers itself as the file handler for CSV files, so it will open in excel by default.

For example:

private void SQLToCSV(string query, string Filename)
{

    SqlConnection conn = new SqlConnection(connection);
    conn.Open();
    SqlCommand cmd = new SqlCommand(query, conn);
    SqlDataReader dr = cmd.ExecuteReader();

    using (System.IO.StreamWriter fs = new System.IO.StreamWriter(Filename))
    {
        // Loop through the fields and add headers
        for (int i = 0; i < dr.FieldCount; i++)
        {
            string name = dr.GetName(i);
            if (name.Contains(","))
                name = "\"" + name + "\"";

            fs.Write(name + ",");
        }
        fs.WriteLine();

        // Loop through the rows and output the data
        while (dr.Read())
        {
            for (int i = 0; i < dr.FieldCount; i++)
            {
                string value = dr[i].ToString();
                if (value.Contains(","))
                    value = "\"" + value + "\"";

                fs.Write(value + ",");
            }
            fs.WriteLine();
        }

        fs.Close();
    }
}

I have modified code which was given above as and is working. Edit according to your requirements

namespace ExcelExport
{

public class ExportToExcel
{
    string strCon = ConfigurationManager.ConnectionStrings["SafewayGVDemoDBContext"].ConnectionString;
    private Microsoft.Office.Interop.Excel.Application app;
    private Microsoft.Office.Interop.Excel.Workbook workbook;
    private Microsoft.Office.Interop.Excel.Worksheet previousWorksheet;
    // private Excel.Range workSheet_range;
    private string folder;

    public ExportToExcel(string folder)
    {

        this.folder = folder;
        this.app = null;
        this.workbook = null;
        this.previousWorksheet = null;
        // this.workSheet_range = null;

        createDoc();
    }

    private void createDoc()
    {
        try
        {
            app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = false;
            workbook = app.Workbooks.Add(1);
        }
        catch (Exception excThrown)
        {
            throw new Exception(excThrown.Message);
        }
        finally
        {
        }
    }

    public void shutDown()
    {
        try
        {
            workbook = null;
            app.Quit();
        }
        catch (Exception excThrown)
        {
            throw new Exception(excThrown.Message);
        }
        finally
        {
        }
    }

    public void ExportTable(string procName, string sheetName)
    {
        SqlDataReader myReader = null;
        try
        {

            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.Add(Missing.Value, Missing.Value, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
            using (SqlConnection Sqlcon = new SqlConnection(strCon))
            {
                SqlCommand cmd = new SqlCommand();
                Sqlcon.Open();
                cmd.Connection = Sqlcon;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = procName;
                cmd.Parameters.Add(new SqlParameter("@pvchAction", SqlDbType.VarChar, 50));
                cmd.Parameters.Add("@pIntErrDescOut", SqlDbType.Int).Direction = ParameterDirection.Output;
                cmd.Parameters["@pvchAction"].Value = "select";
                worksheet.Name = sheetName;
                previousWorksheet = worksheet;

                myReader = cmd.ExecuteReader();

                int columnCount = myReader.FieldCount;

                for (int n = 0; n < columnCount; n++)
                {
                    //Console.Write(myReader.GetName(n) + "\t");
                    createHeaders(worksheet, 1, n + 1, myReader.GetName(n));
                }

                int rowCounter = 2;
                while (myReader.Read())
                {
                    for (int n = 0; n < columnCount; n++)
                    {
                        //Console.WriteLine();
                        //Console.Write(myReader[myReader.GetName(n)].ToString() + "\t");
                        addData(worksheet, rowCounter, n + 1, myReader[myReader.GetName(n)].ToString());
                    }
                    rowCounter++;
                }
            }

        }

        catch (Exception e)
        {
            Console.WriteLine(e.ToString());

        }
        finally
        {
            if (myReader != null && !myReader.IsClosed)
            {
                myReader.Close();
            }
            myReader = null;
        }

    }

    public void createHeaders(Microsoft.Office.Interop.Excel.Worksheet worksheet, int row, int col, string htext)
    {
        worksheet.Cells[row, col] = htext;
    }

    public void addData(Microsoft.Office.Interop.Excel.Worksheet worksheet, int row, int col, string data)
    {
        worksheet.Cells[row, col] = data;
    }

    public void SaveWorkbook()
    {

        String folderPath = @"C:\My Files\" + this.folder;

        if (!System.IO.Directory.Exists(folderPath))
        {
            System.IO.Directory.CreateDirectory(folderPath);
        }

        string fileNameBase = "db";
        String fileName = fileNameBase;
        string ext = ".xlsx";
        int counter = 1;
        //System.IO.File.Open(folderPath + fileName + ext, System.IO.FileMode.Open);
        while (System.IO.File.Exists(folderPath + @"\"+ fileName + ext))
        {
            fileName = fileNameBase + counter;
            counter++;
        }

        fileName = fileName + ext;

        string filePath = folderPath +@"\"+ fileName;

        try
        {
            workbook.SaveAs(filePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());

        }
    }

}

C# SQL to Excel

Call you SP from Database

public DataTable GetDrugUtilizationReport_IndividualGenerateFile(long pharmacyId, DateTime from, DateTime to, long DrugNameId, int sortBy)
{
    var parameters = new Dictionary<string, object>
        {
            { "PharmacyId", pharmacyId },
            { "DateFrom", from },
            { "DateTo", to },
            { "DrugNameId", DrugNameId },
            { "SortBy", sortBy }
        };

    return ExecuteQuery("RPT_DrugUtilizationReportByIndividualGenerateFile", CommandType.StoredProcedure, parameters);
}

Use in your C# Code

private void OnCreateFileCommand(object obj)
{

    string path, parameterLabel;
    path = ConfigurationManager.AppSettings["VSSPORTEXELExportPath"];
    parameterLabel = FromDate.ToString("yyyy-MM-dd") + "_" + ToDate.ToString("yyyy-MM-dd");

    try
    {
        path =
            ExcelUtlity.ExportDataToExcel(
                dataTable:
                    context.GetDrugUtilizationReport_IndividualGenerateFile(GlobalVar.Pharminfo.pharminfo_PK,
                        FromDate, ToDate, SelectedDrug != null ? SelectedDrug.drugnameid_PK : 0,
                        sortBy: SortBy + 1),
                directoryPath: path,
                fileName_withoutExt: "DrugUtilizationReport" + "__" + parameterLabel,
                skipComplexObjects: true,
                skipInheritedProps: true);

        DXMessageBox.Show("Data exported successfully at \"" + path + "\".", GlobalVar.MessageTitle,
            MessageBoxButton.OK, MessageBoxImage.Information);
    }
    catch (Exception ex)
    {
        string errorMessage = ExceptionHelper.ProcessException(ex);
        DXMessageBox.Show(errorMessage, GlobalVar.MessageTitle, MessageBoxButton.OK, MessageBoxImage.Error);
    }

}

Excel Utility

public static string ExportDataToExcel(DataTable dataTable, string directoryPath, string fileName_withoutExt, bool skipComplexObjects, bool skipInheritedProps, string[] skipProps = null)
{
    if (directoryPath[directoryPath.Length - 1] == '\\') // no need to check for >0 length. let it throw an exection for that
        directoryPath = directoryPath + "\\";

    using (var spreadSheet = new SpreadsheetControl())
    {
        // Create new excel document and import the datatable to the worksheet
        spreadSheet.CreateNewDocument();
        spreadSheet.BeginUpdate();
        var worksheet = spreadSheet.Document.Worksheets.ActiveWorksheet;
        worksheet.Import(source: dataTable, addHeader: true, firstRowIndex: 0, firstColumnIndex: 0);

        // applying style on header
        Range range = worksheet.Range["A1:" + worksheet.Columns[worksheet.Columns.LastUsedIndex].Heading+"1"];
        Formatting rangeFormatting = range.BeginUpdateFormatting();
        rangeFormatting.Fill.BackgroundColor = System.Drawing.Color.LightSteelBlue;
        rangeFormatting.Font.FontStyle = SpreadsheetFontStyle.Bold;
        range.AutoFitColumns();
        range.EndUpdateFormatting(rangeFormatting);

        spreadSheet.EndUpdate();
        fileName_withoutExt += ".xlsx";
        Directory.CreateDirectory(directoryPath); // if directory already exists, CreateDirectory will do nothing
        spreadSheet.SaveDocument(directoryPath + fileName_withoutExt, DocumentFormat.OpenXml);

        return directoryPath + fileName_withoutExt;
    }
}

Using Microsoft Office dll

public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string ReporType)
{
    Microsoft.Office.Interop.Excel.Application excel;
    Microsoft.Office.Interop.Excel.Workbook excelworkBook;
    Microsoft.Office.Interop.Excel.Worksheet excelSheet;
    Microsoft.Office.Interop.Excel.Range excelCellrange;

    try
    {
        // Start Excel and get Application object.
        excel = new Microsoft.Office.Interop.Excel.Application();

        // for making Excel visible
        excel.Visible = false;
        excel.DisplayAlerts = false;

        // Creation a new Workbook
        excelworkBook = excel.Workbooks.Add(Type.Missing);

        // Workk sheet
        excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet;
        excelSheet.Name = worksheetName;

        excelSheet.Cells[1, 1] = ReporType;
        excelSheet.Cells[1, 2] = "Date : " + DateTime.Now.ToShortDateString();

        // loop through each row and add values to our sheet
        int rowcount = 2;

        foreach (DataRow datarow in dataTable.Rows)
        {
            rowcount += 1;
            for (int i = 1; i <= dataTable.Columns.Count; i++)
            {
                // on the first iteration we add the column headers
                if (rowcount == 3)
                {
                    excelSheet.Cells[2, i] = dataTable.Columns[i - 1].ColumnName;
                    excelSheet.Cells.Font.Color = System.Drawing.Color.Black;
                }

                excelSheet.Cells[rowcount, i] = datarow[i - 1].ToString();

                //for alternate rows
                if (rowcount > 3)
                {
                    if (i == dataTable.Columns.Count)
                    {
                        if (rowcount % 2 == 0)
                        {
                            excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
                            FormattingExcelCells(excelCellrange, "#CCCCFF", System.Drawing.Color.Black, false);
                        }

                    }
                }
            }
        }

        // now we resize the columns
        excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
        excelCellrange.EntireColumn.AutoFit();
        Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
        border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
        border.Weight = 2d;


        excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[2, dataTable.Columns.Count]];
        FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true);


        //now save the workbook and exit Excel

        excelworkBook.SaveAs(saveAsLocation); ;
        excelworkBook.Close();
        excel.Quit();

        return true;
    }
    catch (Exception ex)
    {
        DXMessageBox.Show(ex.Message);
        return false;
    }
    finally
    {
        excelSheet = null;
        excelCellrange = null;
        excelworkBook = null;
    }

}

/// <summary>
/// FUNCTION FOR FORMATTING EXCEL CELLS
/// </summary>
/// <param name="range"></param>
/// <param name="HTMLcolorCode"></param>
/// <param name="fontColor"></param>
/// <param name="IsFontbool"></param>
public void FormattingExcelCells(Microsoft.Office.Interop.Excel.Range range, string HTMLcolorCode, System.Drawing.Color fontColor, bool IsFontbool)
{
    range.Interior.Color = System.Drawing.ColorTranslator.FromHtml(HTMLcolorCode);
    range.Font.Color = System.Drawing.ColorTranslator.ToOle(fontColor);
    if (IsFontbool == true)
    {
        range.Font.Bold = IsFontbool;
    }
}