c# 按照EXCEL模板把数据导出
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= 2; i++)
{
//生成一个新的文件名用全球唯一标识符 (GUID)来标识
string newpath = Server.MapPath("~/upload/") + Guid.NewGuid() +DateTime.Now.ToString("yyyyMMddhhmmssffff")+ ".xls";
//调用的模板文件
string serv = Server.MapPath("~/excel/test.xls").ToString();
FileInfo mode = new FileInfo(serv);
Excel.Application app = new Excel.Application();
if (app == null)
{
return;
}
app.Application.DisplayAlerts = false;
app.Visible = false;
if (mode.Exists)
{
Excel.Workbook tworkbook;
Object missing = System.Reflection.Missing.Value;
app.Workbooks.Add(missing);
//调用模板
tworkbook = app.Workbooks.Open(mode.FullName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
Excel.Worksheet tworksheet = (Excel.Worksheet)tworkbook.Sheets[2];
tworksheet.Cells[3,4] = "测试";
tworksheet.Cells[3, 5] = "测试2";
Excel.Worksheet tworksheet2 = (Excel.Worksheet)tworkbook.Sheets[3];
tworksheet2.Cells[3, 1] = "测试111";
tworksheet2.Cells[19, 1] = "测试1212";
tworksheet.SaveAs(newpath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
tworkbook.Close(false, mode.FullName, missing);
app.Workbooks.Close();
app.Quit();
if (app != null)
{
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("Excel"))
{
//先判断当前进程是否是excel
if (!p.CloseMainWindow())
{
p.Kill();
}
}
}
tworkbook = null;
app = null;
//强制对所有代进行垃圾回收
GC.Collect();
}
}
//打开保存对话框
//Response.Clear();
//Response.ClearHeaders();
//Response.Buffer = false;
//Response.Charset = "UTF-8";
//Response.ContentType = "application/ms-excel";
//Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(mode.Name));
//Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//Response.AppendHeader("Content-Length", mode.Length.ToString());
//Response.Charset = "";
//this.EnableViewState = false;
//Response.WriteFile(newpath);
//删除创建的Excel文件
//FileInfo fileinf = new FileInfo(newpath);
//fileinf.Delete();
//关闭连接
//Response.Flush();
//Response.End();
}
}
浙公网安备 33010602011771号