我正在尝试创建一个 CLR 过程来将 SQL 数据导出到 Excel,该过程将包含比其他选项(例如小计和突出显示)更多的功能。
这需要我引用Microsoft.Office.Interop.Excel
dll,但我不确定在编译代码时如何实际包含程序集。
如何在我的 CLR 过程中包含 Excel 程序集?
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);
}
}
}
}