必須先添加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”中。您可以根據需要移動(dòng)或移除它。
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中,并且目標文件可以改寫(xiě)
System.IO.File.Copy(templetFile, outputFile, true);
if (this.ExcelRS != null)
ExcelRS = null;
//實(shí)例化ExcelRS對象
ExcelRS = new Excel.ApplicationClass();
if (ExcelRS == null)
{
MessageBox.Show("ERROR: EXCEL couldn 't be started ");
}
//打開(kāi)目標文件outputFile
RSbook = ExcelRS.Workbooks.Open(outputFile, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing, missing);
//設置第一個(gè)工作溥
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();
}
}
}
}