日期:2014-05-18  浏览次数:21154 次

一个关于 asp.net 操作Word的问题???? 请高手指点一下。Microsoft.Office.Interop.Word
我要做的是,在服务器上有一个 Word的模板,在ASP.Net 下在服务端引用
Application application = new ApplicationClass();
Microsoft.Office.Interop.Word.Document doc = new Document();
把Word模板读进来, 之后把模板要替换的地方替换掉。
之后,我不想把他保存在服务器端,在下载。
我想把替换后的 doc 对象 转换成 byte[] 数组 通过 Response.Write()直接输出到 客户端上。
但是不我怎么 把doc 对象 转换成 byte[] 字节数组呢, 有什么方法可以不用在服务器上在生成一个word 文档。
 
我现在做的代码是: 我的意思是 不用在服务器端在生成一个Word 文档。
Application application = new ApplicationClass();
  Microsoft.Office.Interop.Word.Document doc = new Document();

  string outputname = @"D:\WebFileTemp\case{0}.dot";
  Object filename = @"D:\WebFileTemp\case.dot";
  Object outname = String.Format(outputname, (DateTime.Now.Ticks + this.GetHashCode()).ToString());
  Object Nothing = System.Reflection.Missing.Value;
  try
  {
  doc = application.Documents.Open(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

  if (doc.Paragraphs != null && doc.Paragraphs.Count > 0)
  {
  int count = doc.Paragraphs.Count;
  for (int i = 1; i <= count; i++)
  {
  Find find = doc.Paragraphs[i].Range.Find;
  find.ClearFormatting();

  object str = "CASE_CASEID";
  object replacestr = "ddsdsdsddsdsssssssssssssssssssssss" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") ;
  find.Execute(ref str, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref replacestr, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

  }

  }
   
  doc.SaveAs(ref outname, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

   
  }
  catch
  {

  }
  finally
  {
  doc.Close(ref Nothing, ref Nothing, ref Nothing);
  application.Quit(ref Nothing, ref Nothing, ref Nothing);
  }

  byte[] sw = File.ReadAllBytes(outname.ToString());
   

  Response.AddHeader("Content-Disposition", "attachment; filename=List.doc");
  Response.ContentType = "application/msword";
  Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
   
  Response.BinaryWrite(sw);
  Response.End();
  GC.Collect();

------解决方案--------------------
不了解,帮你顶吧。
------解决方案--------------------
byte[] bt = System.Text.Encoding.Default.GetBytes(str)
------解决方案--------------------
你自己的代码就很好了,先产生成一个Word文档也没什么大碍。