//引用
using Microsoft.Office.Tools.Excel;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
//初始化变量
Excel.Application xlApp = null;
Excel.Workbook xlBook = null;
Excel.Workbooks xlBooks = null;
Excel.Worksheet xlSheet = null;
Excel.Range rng_Sno = null;
Excel.Range rng_Sname = null;
Excel.Range rng_address = null;
Excel.Range rng_head = null;
Excel.Range rng_body = null;
Excel.Range rng_Work = null;
//获取实例
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;
xlBooks = xlApp.Workbooks;
xlBooks.Add(true);
xlBook = xlApp.Workbooks.Add(@"E:\temp\OutPutExcel\EXCELTEST1.xlt");
xlSheet = (Excel.Worksheet)xlBook.ActiveSheet;
xlApp.DisplayAlerts = false;
foreach( Excel.Name nn in xlApp.Names)
{
switch (nn.Name)
{
case "head":
rng_head = xlApp.get_Range(nn, Type.Missing);
break;
case "body":
rng_body = xlApp.get_Range(nn, Type.Missing);
break;
case "Sno":
rng_Sno = xlApp.get_Range(nn, Type.Missing);
break;
case "Sname":
rng_Sname = xlApp.get_Range(nn, Type.Missing);
break;
case "address":
rng_address = xlApp.get_Range(nn, Type.Missing);
break;
}
}
//赋值
rng_Sno.set_Item(Type.Missing, Type.Missing, "1");
rng_Sname.set_Item(Type.Missing, Type.Missing, "Jason");
rng_address.set_Item(Type.Missing, Type.Missing, "taicang");
//复制Template body 区域,
rng_body.Rows.EntireRow.Activate();
rng_body.Rows.EntireRow.Cells.Copy(Type.Missing);
//黏贴 Body区域
rng_body.Rows.EntireRow.Insert(XlInsertShiftDirection.xlShiftDown, Type.Missing);
//清空 Body区域
rng_body.Rows.EntireRow.ClearContents();
//赋值 body区域
rng_Sno.set_Item(Type.Missing, Type.Missing, "2");
rng_Sname.set_Item(Type.Missing, Type.Missing, "Ant");
rng_address.set_Item(Type.Missing, Type.Missing, "taicang");
rng_Work = xlSheet.get_Range("A1", Type.Missing);
rng_Work.Select();
xlApp.DisplayAlerts = false;
//保存
xlBook.SaveAs(@"C:\xss\ExcelOutput\test.xls", Excel.XlFileFormat.xlTemplate,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlBook.Close(false, false, Type.Missing);
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(rng_Sno);
System.Runtime.InteropServices.Marshal.ReleaseComObject(rng_Sname);
System.Runtime.InteropServices.Marshal.ReleaseComObject(rng_address);
System.Runtime.InteropServices.Marshal.ReleaseComObject(rng_head);
System.Runtime.InteropServices.Marshal.ReleaseComObject(rng_body);
System.Runtime.InteropServices.Marshal.ReleaseComObject(rng_Work);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBooks);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
System.Diagnostics.Process.Start(@"C:\xss\ExcelOutput\test.xls");
浙公网安备 33010602011771号