Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8129157
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T08:11:13+00:00 2026-06-06T08:11:13+00:00

I am trying to create a CLR procedure to export SQL data to Excel

  • 0

I am trying to create a CLR procedure to export SQL data to Excel that will contain more features than other options such as subtotals and highlighting.

This requires me to reference the Microsoft.Office.Interop.Excel dll, but I’m not sure how to actually include the assembly when I compile my code.

How can I include the Excel assembly in my CLR procedure?

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

public class ExportToExcel
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void ExportQueryResults(string queryText, string worksheetName, string fileName)
{
    using (SqlConnection cnn = new SqlConnection("context connection=true"))
    {
        //the temp list to hold the results in
        List<object[]> results = new List<object[]>();

        cnn.Open();
        //create the sql command
        SqlCommand cmd = new SqlCommand(queryText, cnn);
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            int fieldCount = reader.FieldCount;
            object[] headers = new object[fieldCount];
            for(int i = 0; i < fieldCount; i++)
            {
                headers[i] = reader.GetName(i);
            }

            //read the results
            while (reader.Read())
            {
                object[] values = new object[fieldCount];
                for (int i = 0; i < fieldCount; i++)
                {
                    values[i] = reader[i];
                }
                results.Add(values);
            }

            //convert the results into a 2-d array to export into Excel
            object[,] exportVals = new object[results.Count, fieldCount];

            for (int row = 0; row < results.Count; row++)
            {
                for (int col = 0; col < fieldCount; col++)
                {
                    exportVals[row, col] = results[row][col];
                }
            }

            Excel.Application _app = new Excel.Application();
            Excel.Workbook _book = _app.Workbooks.Add(Missing.Value);
            Excel.Worksheet _sheet = (Excel.Worksheet)_book.ActiveSheet;
            Excel.Range _range = (Excel.Range)_sheet.Cells[1, 1];

            _range = _sheet.get_Range(_sheet.Cells[1, 1], _sheet.Cells[results.Count, fieldCount]);
            _range.Value2 = exportVals;

            _sheet.Name = worksheetName;

            //remove any extra worksheets
            foreach(Excel.Worksheet sht in _book.Worksheets)
            {
                if (sht.Name != worksheetName)
                    sht.Delete();
            }

            _book.SaveAs(fileName
                , Excel.XlFileFormat.xlWorkbookDefault
                , Missing.Value
                , Missing.Value
                , false
                , false
                , Excel.XlSaveAsAccessMode.xlNoChange
                , Missing.Value
                , Missing.Value
                , Missing.Value
                , Missing.Value
                , Missing.Value);
        }
    }
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T08:11:16+00:00Added an answer on June 6, 2026 at 8:11 am

    After a day of fumbling around with nearly every type of error possible, I came up with a solution for my problems.

    I appreciate the answers/comments given, and although I agree there may be more efficient / secure ways of implementing a solution, using the interop assembly was the fastest and most familiar to complete this project.

    Before I get raked over the coals, please realize that auto-filtering and other formatting outside the scope of the more traditional SQL Server export functionality were absolutely required for this project.

    Solution

    I created a class library output type visual studio project titled SqlProcedures, created a new class called ExportToExcel and added Microsoft.Office.Interop.Excel to my references.

    Here is the code in my ExportToExcel.cs file:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Data.SqlClient;
    using Excel = Microsoft.Office.Interop.Excel;
    using System.Reflection;
    using System.Runtime.InteropServices;
    
    public class ExportToExcel
    {
        [Microsoft.SqlServer.Server.SqlProcedure]
    public static void ExportQueryResults(string queryText, string worksheetName, string fileName)
    {
        using (SqlConnection cnn = new SqlConnection("context connection=true"))
        {
            //the temp list to hold the results in
            List<object[]> results = new List<object[]>();
    
            cnn.Open();
            //create the sql command
            SqlCommand cmd = new SqlCommand(queryText, cnn);
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                int fieldCount = reader.FieldCount;
                object[] headers = new object[fieldCount];
                for (int i = 0; i < fieldCount; i++)
                {
                    headers[i] = reader.GetName(i);
                }
    
                //read the results
                while (reader.Read())
                {
                    object[] values = new object[fieldCount];
                    for (int i = 0; i < fieldCount; i++)
                    {
                        values[i] = reader[i];
                    }
                    results.Add(values);
                }
    
                //convert the results into a 2-d array to export into Excel
                object[,] exportVals = new object[results.Count, fieldCount];
    
                for (int row = 0; row < results.Count; row++)
                {
                    for (int col = 0; col < fieldCount; col++)
                    {
                        exportVals[row, col] = results[row][col];
                    }
                }
    
                Excel.Application _app = new Excel.Application();
                Excel.Workbook _book = _app.Workbooks.Add(Missing.Value);
                Excel.Worksheet _sheet = (Excel.Worksheet)_book.ActiveSheet;
                Excel.Range _range = (Excel.Range)_sheet.Cells[1, 1];
                _app.DisplayAlerts = false;
    
                //set the headers and freeze the panes
                _range = _sheet.get_Range(_sheet.Cells[1, 1], _sheet.Cells[1, fieldCount]);
                _range.NumberFormat = "@";
                _range.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                _range.Value2 = headers;
                _range.Font.Bold = true;
                _range = _sheet.get_Range(_sheet.Cells[2, 1], _sheet.Cells[2, 1]);
                _range.EntireRow.Select();
                _range.Application.ActiveWindow.FreezePanes = true;
    
                _range = _sheet.get_Range(_sheet.Cells[2, 1], _sheet.Cells[results.Count, fieldCount]);
                _range.Value2 = exportVals;
    
                _range = _sheet.get_Range(_sheet.Cells[1, 1], _sheet.Cells[exportVals.Length, fieldCount]);
                _range.AutoFilter(1, Type.Missing, Excel.XlAutoFilterOperator.xlAnd, Type.Missing, true);
                _sheet.Cells.Columns.AutoFit();
                _sheet.Range["A1"].Select();
    
                _sheet.Name = worksheetName;
    
                //remove any extra worksheets
                foreach (Excel.Worksheet sht in _book.Worksheets)
                {
                    if (sht.Name != worksheetName)
                        sht.Delete();
                }
    
                _book.SaveAs(fileName
                    , Excel.XlFileFormat.xlExcel5
                    , Missing.Value
                    , Missing.Value
                    , false
                    , false
                    , Excel.XlSaveAsAccessMode.xlNoChange
                    , Missing.Value
                    , Missing.Value
                    , Missing.Value
                    , Missing.Value
                    , Missing.Value);
    
                //_book.Close(Missing.Value, Missing.Value, Missing.Value);
                _app.Application.Quit();
    
                GC.Collect();
                GC.WaitForPendingFinalizers();
    
                Marshal.ReleaseComObject(_range);
                Marshal.ReleaseComObject(_sheet);
                Marshal.ReleaseComObject(_book);
                Marshal.ReleaseComObject(_app);
    
                _range = null;
                _sheet = null;
                _book = null;
                _app = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
    }
    }
    

    After sucessfully building the DLL, I copied it to a local directory on my SQL server.

    In order to run the procedure ExportQueryResults, I needed to add several assemblies in the SQL server that the Microsoft.Office.Interop.Excel.dll depends on.

    Here is my SQL code:

    ALTER DATABASE main SET TRUSTWORTHY ON;
    
    create assembly [stdole] from
    'C:\Program Files\Microsoft.NET\Primary Interop Assemblies\stdole.dll'
    WITH PERMISSION_SET = unsafe
    create assembly [Office] from
    'C:\WINDOWS\assembly\GAC\office\12.0.0.0__71e9bce111e9429c\OFFICE.DLL'
    WITH PERMISSION_SET = unsafe
    
    create assembly [Vbe] 
        FROM 'C:\WINDOWS\assembly\GAC\Microsoft.Vbe.Interop\12.0.0.0__71e9bce111e9429c\Microsoft.Vbe.Interop.dll'
    WITH PERMISSION_SET = unsafe
    
    
    create assembly [Microsoft.Office.Interop.Excel.dll] 
    from 'C:\WINDOWS\assembly\GAC\Microsoft.Office.Interop.Excel\12.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll'
    WITH PERMISSION_SET = unsafe
    
    create assembly SqlProcedures from 'c:\sql_data_reporting\SqlProcedures.dll'
    WITH PERMISSION_SET = unsafe
    go
    create procedure ExportToExcel @queryText nvarchar(4000), @worksheetName nvarchar(32),     @fileName nvarchar(250)
    as external name SqlProcedures.ExportToExcel.ExportQueryResults
    go
    

    Now I know that using with permission_set = unsafe is a nono, but this was a “get it done now” project, and this was the fastest solution I could come up with.

    Hopefully this solution will save some time for others who need to implement similar functionality.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

we are trying to create C# CLR Stored Procedure on a SQL Server 2005
I'm trying to create a SQL Server CLR user-defined function that connects to a
I'm trying to create a SQL Server CLR user-defined function that connects to a
I am trying to create a WiX custom action which will allow me to
Problem I'm trying to create an CUDA application that is well integrated with .net.
I am facing this error, Cannot create unknown Type '{clr- namespace:ActivityLibrary1;assembly=ActivityLibrary1}MyActivity1' while trying to
I'm trying to create my own ChildWindow whith BusyIndicator. This ChildWindow will be a
I am trying to create a User Control that, depending on the mode the
I'm trying to write a CLR user-defined function in F#, but CREATE ASSEMBLY gives
I'm trying to create a UserControl that inherits from a generic class. It does

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.