必须先添加COM中的EXCEL引用
如micrsoft.excel.11 ,还有microsoft.office.11
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Excel;
using Microsoft.Office.Core;
using System.IO;
using System.Reflection;
namespace WindowsApplication15
{
public partial class Form1 : Form
{
private object missing = Missing.Value;
private Excel.Application ExcelRS;
private Excel.Workbook RSbook;
private Excel.Worksheet RSsheet;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: 这行代码将数据加载到表“nSPGDataSet.SWRY”中。您可以根据需要移动或移除它。
this.sWRYTableAdapter.Fill(this.nSPGDataSet.SWRY);
}
private void button1_Click(object sender, EventArgs e)
{
string OutFilePath = @"c:\lyx1.xls";
string TemplateFilePath = @"c:\模版.xls";
PrintInit(TemplateFilePath, OutFilePath);
}
public void PrintInit(string templetFile, string outputFile)
{
try
{
if (templetFile == null)
{
MessageBox.Show("Excel模板文件路径不能为空!");
}
if (outputFile == null)
{
MessageBox.Show("输出Excel文件路径不能为空!");
}
//把模版文件templetFile拷贝到目输出文件outputFile中,并且目标文件可以改写
System.IO.File.Copy(templetFile, outputFile, true);
if (this.ExcelRS != null)
ExcelRS = null;
//实例化ExcelRS对象
ExcelRS = new Excel.ApplicationClass();
if (ExcelRS == null)
{
MessageBox.Show("ERROR: EXCEL couldn 't be started ");
}
//打开目标文件outputFile
RSbook = ExcelRS.Workbooks.Open(outputFile, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing, missing);
//设置第一个工作溥
RSsheet = (Excel.Worksheet)RSbook.Sheets.get_Item(1);
////激活当前工作溥
//RSsheet.Activate();
for (int i = 0; i < this.dataGridView1.RowCount - 1; i++)
{
// MessageBox.Show(this.dataGridView1[0, i].Value.ToString() + this.dataGridView1[1, i].Value.ToString());
RSsheet.Cells[3 + i, 1] = this.dataGridView1[0, i].Value.ToString();
RSsheet.Cells[3 + i, 2] = this.dataGridView1[1, i].Value.ToString();
}
//保存目标文件
//RSbook.Save();
RSbook.Close(true, missing, missing);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(RSsheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(RSbook);
//设置DisplayAlerts
ExcelRS.DisplayAlerts = false;
ExcelRS.Visible = true;
//ExcelRS.DisplayAlerts = true;
//释放对象
RSsheet = null;
RSbook = null;
ExcelRS.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelRS);
ExcelRS = null;
GC.Collect();
}
}
}
}