C#实现按Word模板导出Word(加书签bookMark)

时间:2021-03-08 05:05:46

本方法是针对word导出操作,需要制作好的模板文件 模板.doc

引入应用Microsoft.Office.Interop.Word 11.0  (office2003)

导出文件注意:有时候迅雷会在浏览器中安装插件,下载时会默认使用迅雷下载,导致下载的文档格式丢失,这时为了避免错误,可以将下载方法DownFile()写在另一个页面中,通过session将参数传递过去就可以

 /// <summary>
/// 导出按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{ string id;
id = Session["ObjChangeID"].ToString();
try
{ if (id!=null)
{ string _filePath = PrintDoc(id);
if (_filePath != "")
{
DownloadFile(_filePath, Path.GetFileName(_filePath));//下载文件
}
}
}
catch (Exception ex)
{
ZWL.Common.PublicMethod.errorLog("ibtnExport_Click", ex);
}
}
/// <summary>
/// 打印操作,传入车辆Carcod或者变更ID
/// </summary>
/// <param name="id"></param>
protected string PrintDoc(string id)
{
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
try
{ if (id.Length != )
{
objCarInfor.OpenCar(id);
string templeteName = "模版.doc", downName = "";///模板文件名称
downName = objCarInfor.ORG_NAME + "新文件.doc";//导出文件名 string templeteFile = System.Web.HttpContext.Current.Server.MapPath("~/") + "DocTempalete\\" + templeteName;//模板文件全路径
string downFile = System.Web.HttpContext.Current.Server.MapPath("~/") + "ReportFile\\gonghan\\" + downName;///导出文件全路径
try
{
File.Delete(downFile);//删除原有的同名文件
}
catch
{
}
File.Copy(templeteFile, downFile);//复制模板文件到导出文件对应的文件夹下存档
object Obj_FileName = downFile;
object Visible = false;
object ReadOnly = false;
object missing = System.Reflection.Missing.Value;
//打开文件
doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref Visible,
ref missing, ref missing, ref missing,
ref missing);
doc.Activate();
#region 给模板填入类容
//光标转到书签
object BookMarkName = "函号";
object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark; if (app.ActiveDocument.Bookmarks.Exists(BookMarkName.ToString()) == true)
{
doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref BookMarkName);
doc.ActiveWindow.Selection.TypeText(System.DateTime.Now.ToString("yyMMdd"));
}
BookMarkName = "年";
what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark; if (app.ActiveDocument.Bookmarks.Exists(BookMarkName.ToString()) == true)
{
doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref BookMarkName);
doc.ActiveWindow.Selection.TypeText(DateTime.Now.ToString("yy"));
}
BookMarkName = "月";
what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark; if (app.ActiveDocument.Bookmarks.Exists(BookMarkName.ToString()) == true)
{
doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref BookMarkName);
doc.ActiveWindow.Selection.TypeText(DateTime.Now.ToString("MM"));
}
BookMarkName = "日";
what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark; if (app.ActiveDocument.Bookmarks.Exists(BookMarkName.ToString()) == true)
{
doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref BookMarkName);
doc.ActiveWindow.Selection.TypeText(DateTime.Now.ToString("dd"));
}
///注意:书签必须不一样才能真确绑定,如果说模板中有需要出现两次的的内容,必须设置成两个标签:
/// 如:姓名显示两次,则必须给两个位置都加上标签,以示区别
259 #endregion
object IsSave = true;
doc.Close(ref IsSave, ref missing, ref missing);///关闭doc文档对象
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc); doc = null; object IsSave1 = false;
app.Quit(ref IsSave1, ref missing, ref missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
GC.Collect();
return downFile;
}
else
{
return "";
} }
catch (Exception ex)
{
app = null;
GC.Collect();
return "";
} }
///
/// <summary>
/// 下载文件
/// </summary>
/// <param name="filename">文件名(全路径)</param>
/// <param name="downname">文件下载名</param>
protected void DownloadFile(string filename, string downname)
{
FileStream f;
byte[] buffer = new byte[];
try
{
f = new FileStream(filename, FileMode.Open);
buffer = new byte[f.Length];
f.Read(buffer, , buffer.Length);
f.Close();
}
catch
{
ZWL.Common.MessageBox.Show(this, "文件不存在!");
return;
} filename = filename.Replace(@"/", @"\");
//20121023wangyj string saveFileName = "";
int intStart = filename.LastIndexOf("\\") + ;
saveFileName = filename.Substring(intStart, filename.Length - intStart); Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312"; string fileType = Path.GetExtension(filename).ToLower(); switch (fileType)
{
case ".asf":
System.Web.HttpContext.Current.Response.ContentType = "video/x-ms-asf";
break;
case ".jpg":
case ".jpeg":
System.Web.HttpContext.Current.Response.ContentType = "image/jpeg";
break;
case ".gif":
System.Web.HttpContext.Current.Response.ContentType = "image/gif";
break;
case ".pdf":
System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
break;
case ".avi":
System.Web.HttpContext.Current.Response.ContentType = "video/avi";
break;
case ".doc":
System.Web.HttpContext.Current.Response.ContentType = "application/msword";
break;
case ".zip":
System.Web.HttpContext.Current.Response.ContentType = "application/zip";
break;
case ".rar":
System.Web.HttpContext.Current.Response.ContentType = "application/rar";
break;
case ".xls":
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
break;
case ".wav":
System.Web.HttpContext.Current.Response.ContentType = "audio/wav";
break;
case ".mp3":
System.Web.HttpContext.Current.Response.ContentType = "audio/mpeg3";
break;
case ".mpg":
System.Web.HttpContext.Current.Response.ContentType = "audio/mpeg";
break;
case ".rtf":
System.Web.HttpContext.Current.Response.ContentType = "application/rtf";
break;
case ".htm":
case ".html":
System.Web.HttpContext.Current.Response.ContentType = "text/html";
break;
case ".asp":
System.Web.HttpContext.Current.Response.ContentType = "text/asp";
break;
default:
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
break;
} Response.HeaderEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(downname));
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //Response.WriteFile(System.Configuration.ConfigurationSettings.AppSettings["TemplatePhysicalPath"].ToString() + pt.Path);
Response.BinaryWrite(buffer);
Response.GetHashCode();
Response.End();
}