Вот код функции, осуществляющей экспорт в моем проекте
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop;
using System.Threading;
public void ExportToExcel()
{
ApplicationClass Excel = new ApplicationClass();
XlReferenceStyle RefStyle = Excel.ReferenceStyle;
Excel.Visible = true;
Workbook wb = null;
String TemplatePath = System.Windows.Forms.Application.StartupPath + @"\Экспорт данных.xlt";
try
{
wb = Excel.Workbooks.Add(TemplatePath); // !!!
}
catch (System.Exception ex) { throw new Exception("Не удалось загрузить шаблон для экспорта " + TemplatePath); }
Worksheet ws = wb.Worksheets.get_Item(1) as Worksheet ;
for (int j = 0; j < GridView.Columns.Count; ++j)
{
(ws.Cells[1, j + 1] as Range).Value2 = GridView.Columns[j].HeaderText;
for (int i = 0; i < GridView.Rows.Count; ++i) {
object Val = GridView.Rows[i].Cells[j].Value;
if (Val != null)
(ws.Cells[i + 2, j + 1] as Range).Value2 = Val.ToString();
}
}
Excel.ReferenceStyle = RefStyle;
ReleaseExcel(Excel as Object);
}
private void ReleaseExcel(object excel)
{
// Уничтожение объекта Excel.
Marshal.ReleaseComObject(excel);
// Вызываем сборщик мусора для немедленной очистки памяти
GC.GetTotalMemory(true);
}