c#操作word表格

来源:互联网 发布:深圳益玩网络 编辑:程序博客网 时间:2024/04/25 02:38

最近由于工作需要,做了一些关于c#操作word文档方面的工作.主要是对word中表格的操作,以下是部分代码,关于操作不规则表格的.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;

using System.Reflection;
using System.Runtime.InteropServices ;
using System.Threading;

public void MakeMyTable(DataTable DT,string strFilePath)
  {
   
   string strEnd   = this.txtEnd.Text.Trim().ToString();
   string strStart = this.txtStart.Text.Trim().ToString();
//生成文档分页中的起始和终止页
   string strSign = "("+strStart + "-" + strEnd + ")";

   //杀掉所有word进程以保证速度
   //KillWordProcess();

   object Nothing = System.Reflection.Missing.Value;
   object missing = System.Reflection.Missing.Value;
   object filename= strFilePath; 

   Word.Application wordApp=new Word.ApplicationClass();
   Word.Document wordDoc=wordApp.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);

   try
   {
    //生成过程中屏蔽返回按扭,不允许中途停止
    Button2.Enabled = false;
    #region 生成文档
    //设置文档宽度
    wordApp.Selection.PageSetup.LeftMargin  = wordApp.CentimetersToPoints(float.Parse("2"));
    wordApp.ActiveWindow.ActivePane.HorizontalPercentScrolled = 11 ;
    wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2"));

    Object start = Type.Missing;
    Object end = Type.Missing;
    Object unit = Type.Missing;
    Object count = Type.Missing;
    wordDoc.Range(ref start, ref end).Delete(ref unit, ref count);


    object rng = Type.Missing;
    string strInfo = this.txtNameCh.Text.ToString()+"明细表"+strSign+"/r/n";
    start = 0;
    end = 0;
    wordDoc.Range(ref start, ref end).InsertBefore(strInfo);
    wordDoc.Range(ref start, ref end).Font.Name = "Verdana";
    wordDoc.Range(ref start, ref end).Font.Size = 20;
    wordDoc.Range(ref start, ref end).ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;

    start = 8;
    end = strInfo.Length;
    wordDoc.Range(ref start, ref end).InsertParagraphAfter();//插入回车

    if(DT.Rows.Count>0)
    {
     //存在数据项
     //添加一个表格
     object missingValue = Type.Missing;
     object location = strInfo.Length; //注:若location超过已有字符的长度将会出错。一定要比"明细表"串多一个字符
     Word.Range rng2 = wordDoc.Range(ref location, ref location);

     wordDoc.Tables.Add(rng2, 13, 6, ref missingValue, ref missingValue);
     wordDoc.Tables.Item(1).Rows.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
     wordDoc.Tables.Item(1).Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));
     wordDoc.Tables.Item(1).Range.Font.Size = 10;
     wordDoc.Tables.Item(1).Range.Font.Name = "宋体";
     wordDoc.Tables.Item(1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
     wordDoc.Tables.Item(1).Range.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
     //设置表格样式
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).Color = Word.WdColor.wdColorAutomatic;
     
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).Color = Word.WdColor.wdColorAutomatic;

     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).Color = Word.WdColor.wdColorAutomatic;

     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).Color = Word.WdColor.wdColorAutomatic;

     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).Color = Word.WdColor.wdColorAutomatic;
     
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
     wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).Color = Word.WdColor.wdColorAutomatic;

     //     wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
     //     wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
     //     wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).Color = Word.WdColor.wdColorAutomatic;
     //第一行显示
     wordDoc.Tables.Item(1).Cell(1,2).Merge(wordDoc.Tables.Item(1).Cell(1,3));
     wordDoc.Tables.Item(1).Cell(1,4).Merge(wordDoc.Tables.Item(1).Cell(1,5));

     //第二行显示
     wordDoc.Tables.Item(1).Cell(2,5).Merge(wordDoc.Tables.Item(1).Cell(2,6));
     wordDoc.Tables.Item(1).Cell(1,4).Merge(wordDoc.Tables.Item(1).Cell(2,5));

     #region 插入数据行
     wordDoc.Tables.Item(1).Cell(1, 1).Range.Text = "cell11";
     //wordDoc.Tables.Item(k).Cell(1, 2).Range.Text = DT.Rows[i]["cell11"].ToString();

 

     ////******************
     wordDoc.Tables.Item(1).Cell(1, 3).Range.Text = "cell13";
     //wordDoc.Tables.Item(k).Cell(1, 4).Range.Text = DT.Rows[i]["cell13"].ToString();

 

     ////******************
     wordDoc.Tables.Item(1).Cell(2, 1).Range.Text = "cell21";
     //wordDoc.Tables.Item(k).Cell(2, 2).Range.Text = DT.Rows[i]["cell21"].ToString();


     ////******************
     wordDoc.Tables.Item(1).Cell(2, 3).Range.Text = "cell23";
     //wordDoc.Tables.Item(k).Cell(2, 4).Range.Text = DT.Rows[i]["cell23"].ToString();

     #endregion


     #region 第三行显示
     wordDoc.Tables.Item(1).Cell(3,2).Merge(wordDoc.Tables.Item(1).Cell(3,3));
     wordDoc.Tables.Item(1).Cell(3,2).Merge(wordDoc.Tables.Item(1).Cell(3,3));

     ////******************
     wordDoc.Tables.Item(1).Cell(3, 1).Range.Text = "cell31";
     
     

 

     ////******************
     wordDoc.Tables.Item(1).Cell(3, 3).Range.Text = "cell33";
     

     #endregion


     #region 第五行显示
     wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
     wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
     wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
     wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
     #endregion


     #region  第四行显示

     ////******************
     wordDoc.Tables.Item(1).Cell(4, 1).Range.Text = "cell41";
     

 

     ////******************
     wordDoc.Tables.Item(1).Cell(4, 3).Range.Text = "cell43";
     

 

     ////******************
     wordDoc.Tables.Item(1).Cell(4, 5).Range.Text = "cell45";
     
     #endregion


     #region 第六行显示
     wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
     wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
     wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
     wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));


     ////******************
     wordDoc.Tables.Item(1).Cell(5, 1).Range.Text = "cell51";
     
     wordDoc.Tables.Item(1).Cell(5, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

 

     ////******************
     wordDoc.Tables.Item(1).Cell(6, 1).Range.Text = "cdll61";
     
     wordDoc.Tables.Item(1).Cell(6, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
     #endregion


     #region 第七行显示
     wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
     wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
     wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
     wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));

     ////******************
     wordDoc.Tables.Item(1).Cell(7, 1).Range.Text = "cell71";
     
     wordDoc.Tables.Item(1).Cell(7, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
     #endregion


     #region 第八行显示
     wordDoc.Tables.Item(1).Cell(8,1).Merge(wordDoc.Tables.Item(1).Cell(8,2));
     wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));
     wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));
     wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));

     
     #endregion


     #region 第九行显示
     wordDoc.Tables.Item(1).Cell(9,1).Merge(wordDoc.Tables.Item(1).Cell(9,2));
     wordDoc.Tables.Item(1).Cell(9,3).Merge(wordDoc.Tables.Item(1).Cell(9,4));

     ////******************
     wordDoc.Tables.Item(1).Cell(9, 1).Range.Text = "cell91";
     //wordDoc.Tables.Item(k).Cell(9, 2).Range.Text =  (DT.Rows[i]["cell91"].ToString()=="1"?"有":"无");

 


     ////******************
     wordDoc.Tables.Item(1).Cell(9, 3).Range.Text = "cell93";
   
     #endregion


     #region 第十行显示
     wordDoc.Tables.Item(1).Cell(10,1).Merge(wordDoc.Tables.Item(1).Cell(10,2));
     wordDoc.Tables.Item(1).Cell(10,3).Merge(wordDoc.Tables.Item(1).Cell(10,4));
     ////******************
     wordDoc.Tables.Item(1).Cell(10, 1).Range.Text = "cell101";
     

 

     ////******************
     wordDoc.Tables.Item(1).Cell(10, 3).Range.Text = "cdll103";
     //wordDoc.Tables.Item(k).Cell(10, 4).Range.Text = (DT.Rows[i]["Label"].ToString()=="1"?"有":"无");
     #endregion


     #region 第十一行显示
     wordDoc.Tables.Item(1).Cell(11,1).Merge(wordDoc.Tables.Item(1).Cell(11,2));
     wordDoc.Tables.Item(1).Cell(11,3).Merge(wordDoc.Tables.Item(1).Cell(11,4));
     ////******************
     wordDoc.Tables.Item(1).Cell(11, 1).Range.Text = "cell111";
     


     ////******************
     wordDoc.Tables.Item(1).Cell(11, 3).Range.Text = "cell113";
   
     #endregion


     #region 第十二行显示
     wordDoc.Tables.Item(1).Cell(12,1).Merge(wordDoc.Tables.Item(1).Cell(12,2));
     wordDoc.Tables.Item(1).Cell(12,3).Merge(wordDoc.Tables.Item(1).Cell(12,4));
     ////******************
     wordDoc.Tables.Item(1).Cell(12, 1).Range.Text = "cell121";
     

     ////******************
     wordDoc.Tables.Item(1).Cell(12, 3).Range.Text = "cell123";

     #endregion


     #region 第十三行显示
     wordDoc.Tables.Item(1).Cell(13,1).Merge(wordDoc.Tables.Item(1).Cell(13,2));
     wordDoc.Tables.Item(1).Cell(13,3).Merge(wordDoc.Tables.Item(1).Cell(13,4));

     ////******************
     wordDoc.Tables.Item(1).Cell(13, 1).Range.Text = "cell131";
     

     ////******************
     wordDoc.Tables.Item(1).Cell(13, 3).Range.Text = "cell133";
  
     #endregion

     wordDoc.Tables.Item(1).Select();
     wordApp.Application.Selection.Cut();

     //重新成声所有表

   
     

     for(int i = 0; i<=DT.Rows.Count-1;i++)
     {
      wordApp.Application.Selection.Paste();
      int k = i+1;
      #region    更新数据


      #region 插入数据行
      
      wordDoc.Tables.Item(k).Cell(1, 2).Range.Text = DT.Rows[i]["1"].ToString();

 

      ////******************
      
      wordDoc.Tables.Item(k).Cell(1, 4).Range.Text = DT.Rows[i]["2"].ToString();

 

      ////******************
      
      wordDoc.Tables.Item(k).Cell(2, 2).Range.Text = DT.Rows[i]["3"].ToString();


      ////******************
      
      wordDoc.Tables.Item(k).Cell(2, 4).Range.Text = DT.Rows[i]["4"].ToString();

      #endregion


      #region 第三行显示
      ////******************
      
      wordDoc.Tables.Item(k).Cell(3, 2).Range.Text = DT.Rows[i]["5"].ToString();
      ////******************
      
      wordDoc.Tables.Item(k).Cell(3, 4).Range.Text = DT.Rows[i]["6"].ToString();

      #endregion


      #region 第五行显示
      ////******************
      
      wordDoc.Tables.Item(k).Cell(5, 2).Range.Text = DT.Rows[i]["7"].ToString();
      wordDoc.Tables.Item(k).Cell(5, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
      #endregion

      #region  第四行显示

      ////******************
      
      wordDoc.Tables.Item(k).Cell(4, 2).Range.Text = DT.Rows[i]["8"].ToString();

 

      ////******************
      
      wordDoc.Tables.Item(k).Cell(4, 4).Range.Text = DT.Rows[i]["9"].ToString();

 

      ////******************
      
      wordDoc.Tables.Item(k).Cell(4, 6).Range.Text = DT.Rows[i]["0"].ToString();
      #endregion


      #region 第六行显示
      ////******************
      
      wordDoc.Tables.Item(k).Cell(6, 2).Range.Text = DT.Rows[i]["11"].ToString();
      wordDoc.Tables.Item(k).Cell(6, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
      #endregion


      #region 第七行显示
      ////******************
      
      wordDoc.Tables.Item(k).Cell(7, 2).Range.Text = DT.Rows[i]["12"].ToString();
      wordDoc.Tables.Item(k).Cell(7, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
      #endregion


      #region 第八行显示
      ////******************
      
      string strTechlevel = DT.Rows[i]["Level"].ToString();
      string returnTechlevel = "";
      switch(strTechlevel)
      {
       case "1":
        returnTechlevel = "Level1";
        break;
       case "2":
        returnTechlevel = "Level2";
        break;
       case "3":
        returnTechlevel = "Level3";
        break;
       case "0":
        returnTechlevel = "Level4";
        break;
       default:
        returnTechlevel = "Level5";
        break;
      }
      wordDoc.Tables.Item(k).Cell(8, 2).Range.Text = returnTechlevel;

      #endregion


      #region 第九行显示
      ////******************
      
      wordDoc.Tables.Item(k).Cell(9, 2).Range.Text =  (DT.Rows[i]["14"].ToString()=="1"?"有":"无");

 


      ////******************
      
      wordDoc.Tables.Item(k).Cell(9, 4).Range.Text = (DT.Rows[i]["15"].ToString()=="1"?"是":"否");
      #endregion


      #region 第十行显示
      ////******************
      
      wordDoc.Tables.Item(k).Cell(10, 2).Range.Text =  (DT.Rows[i]["16"].ToString()=="1"?"有":"无");

 

      ////******************
      
      wordDoc.Tables.Item(k).Cell(10, 4).Range.Text = (DT.Rows[i]["17"].ToString()=="1"?"有":"无");
      #endregion


      #region 第十一行显示

      ////******************
      
      wordDoc.Tables.Item(k).Cell(11, 2).Range.Text =  (DT.Rows[i]["18"].ToString()=="1"?"是":"否");


      ////******************
      
      wordDoc.Tables.Item(k).Cell(11, 4).Range.Text = (DT.Rows[i]["19"].ToString()=="1"?"是":"否");
      #endregion


      #region 第十二行显示
      ////******************
      
      wordDoc.Tables.Item(k).Cell(12, 2).Range.Text =  (DT.Rows[i]["20"].ToString()=="1"?"是":"否");

      ////******************
      
      wordDoc.Tables.Item(k).Cell(12, 4).Range.Text =  (DT.Rows[i]["21"].ToString()=="1"?"是":"否");
      #endregion


      #region 第十三行显示
     
      
      wordDoc.Tables.Item(k).Cell(13, 2).Range.Text =  (DT.Rows[i]["22"].ToString()=="1"?"是":"否");

      ////******************
      
      wordDoc.Tables.Item(k).Cell(13, 4).Range.Text =  (DT.Rows[i]["23"].ToString()=="1"?"是":"否");
      #endregion

      #endregion

      //插入分页
      if(i!=DT.Rows.Count-1)
      {
       object mymissing = System.Reflection.Missing.Value;
       object myunit = Word.WdUnits.wdStory;
       wordApp.Selection.EndKey(ref myunit,ref mymissing);

       object pBreak= (int)Word.WdBreakType.wdPageBreak;
       wordApp.Selection.InsertBreak( ref pBreak );
      }
     }
    

     wordDoc.SaveAs(ref filename, ref missing,ref missing, ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing, ref missing);
   
   
     wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
     wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

     if ( wordDoc != null )
     {
      System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
      wordDoc = null;
     }
     if ( wordApp != null )
     {
      System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
      wordApp = null;
     }
     GC.Collect();
     //KillWordProcess();
     string strUrl = "MakeWordFile.aspx?username="+Request.QueryString["username"].ToString();
     utility.ShowPopMessage("文档生成完毕!",strUrl);
    }
    else
    {
     utility.ShowPopMessage("无任何数据!");
    }
    #endregion

   

   }
   catch
   {
    wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
    wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
    if ( wordDoc != null )
    {
     System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
     wordDoc = null;
    }
    if ( wordApp != null )
    {
     System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
     wordApp = null;
    }
    GC.Collect();
    utility.ShowPopMessage("文档生成失败!");

   }
  }

 

接上一篇,这是关于书签的操作.

/// <summary>
  /// 打印商品
  /// </summary>
  /// <param name="strUserName"></param>
  /// <param name="strPackId"></param>
  private void MakeWordFile(string strUserName,string strPackId)
  {
   try
   {
   
    EnDoc ED = new EnDoc();

    ED.DotPath = Server.MapPath(@"../Product/一览表.doc");
    string path= Server.MapPath(@"../PrintProduct/");
    if(!Directory.Exists(path))
    {
     Directory.CreateDirectory(path);
    }
    ED.OpenFile();
    string strSqlText = "查询语句"; //在该处写查询语句
    DataTable myDataTable = new DataTable();
    myDataTable = MC.Getdt(strSqlText);  //数据库操作类,返回datatable类型数据
    
    DataTable DT = new DataTable();
    DT.Columns.Add("ID",Type.GetType("System.Int32"));
    DataColumn[] pk = new DataColumn[1];
    pk[0] = DT.Columns["ID"];
    DT.PrimaryKey = pk;
    DT.Columns["ID"].AutoIncrement = true;
    DT.Columns["ID"].AutoIncrementSeed = 1;
    DT.Columns["ID"].ReadOnly = true;
    DT.Columns.Add("ID",Type.GetType("System.String"));
    DT.Columns.Add("Name",Type.GetType("System.String"));
    DT.Columns.Add("Num",Type.GetType("System.String"));
     
    DataRow TempRow;
    for (int i=0 ;i< myDataTable.Rows.Count;i++)
    {
     TempRow = DT.NewRow();
     TempRow[""] = myDataTable.Rows[i]["ID"];
     TempRow["Name"] = myDataTable.Rows[i]["Name"];
     TempRow["Num"] = myDataTable.Rows[i]["Num"];
     DT.Rows.Add(TempRow);
    }
    object lblName = "ProviderName";
    ED.WriteData(ref lblName,"UserName"); //在书签处替换
    ED.FillTable(DT,2,4,2);

    string strFileName = strUserName + DateTime.Now.ToString("yyyyMMddHHmmss") +".doc";   

    object fileName = path + strFileName;
    strFileName = "../PrintProduct/" + strFileName;
    ED.SaveAs(ref fileName);
    ED.Quit();
    
    Response.Write("<Script language = 'javascript'>window.open('");
    Response.Write(strFileName);
    Response.Write("')</script>");
 
   }
   catch(Exception ex)
   {
    Response.Write("<script language = 'javascript'>alert('"+ex.Message+"');</script>");
   }   
  }

*****************************888

EnDoc类

using System;
using Word;
using System.Reflection;
using System.Runtime.InteropServices ;
using System.Data ;
using System.Configuration;
using System.IO;

namespace SchDeposit.FuncClass
{
 /// <summary>
 /// EnDoc 的摘要说明。
 /// </summary>
 public class EnDoc
 {
  public EnDoc()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }
  [DllImport ("user32.dll")]  
  public static extern int MessageBox(int h,string m,string c,int type);
  Word.ApplicationClass app = new Word.ApplicationClass();
  object optional=Missing.Value;
  object visible=true;
  object saveChanges = true;
  object NOTsaveChanges = false;
  object docreadonly=true;
  object originalFormat = Missing.Value;
  object routeDocument = Missing.Value;
  _Document doc=null;
  //  FillCtl f=new FillCtl ();

  private string dotpath;
  public  string DotPath
  {
   get
   {
    return dotpath;
   }
   set
   {
    dotpath=value;
   }
  }  
  private string GetData(string str)
  {
   if (str==null)
    str="";
   else
    str=str.Trim();
   return str;
  }

  #region ******打开文件*******
  public bool OpenFile()
  {
   try
   {
    if (File.Exists(dotpath)==true)
    {
     object fileName = dotpath;
     doc = app.Documents.Open(ref fileName,ref optional,ref docreadonly,ref optional,ref optional,ref optional,ref optional,ref optional,ref optional,ref optional,ref optional, ref visible);
     return true;
    }
    else
     MessageBox(0,"文件不存在!" ,"Error Message Box",0);
    return  false;
   }
   catch (System.Exception e)
   {
    throw new Exception (e.Message );
   }
  }
  #endregion

  #region ******写入数据*******
  public void WriteData(ref object lbl,string txt)
  {//向标签lbl中写入数据txt
   try
   {
    doc.Bookmarks.Item(ref lbl).Select();
    doc.Application.Selection.TypeText(txt.Trim());
   }
   catch (System.Exception e)
   {
    doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);
    throw new Exception (e.Message );
   }
  }
  public void WriteData(DataTable dt)
  {//将DataTable的第一行数据顺序写入文档的标签
   try
   { 
    if (dt.Rows.Count >=1)
    {
     object[] lbl=GetMark ();
     if (lbl.Length ==dt.Columns.Count)
      for (int i=0;i<lbl.Length;i++ )
       WriteData (ref lbl[i],dt.Rows[0][i].ToString ()); 
     else
      MessageBox(0, "长度不符" ,"Error Message Box",0);
    }
   }
   catch (System.Exception e)
   {
    doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);
    throw new Exception (e.Message );
   }
  }

  #endregion

  #region ******向表格写入数据*******
  /// <summary>
  ///
  /// </summary>
  /// <param name="dt">DataTable</param>
  /// <param name="beginRow">开始写入的起始行</param>
  /// <param name="Cols">填充的列数</param>
  /// <param name="TablesItem">表格在word中的序号,从1开始</param>
  /// <returns></returns>
  public bool FillTable(DataTable dt,int beginRow,int Cols,int TablesItem)
  {
   try
   {
    object row =1;
    TablesItem=app.Application.ActiveDocument.Tables.Count;
    int xb=0;
    for (int i=0; i<dt.Rows.Count; i++)
    {
     app.Application.ActiveDocument.Tables.Item(TablesItem).Cell (beginRow + i,1).Select ();
     app.Application.Selection.InsertRowsBelow (ref row);
     app.Application.Selection.Text=GetData(dt.Rows[xb][0].ToString());     
     for (int j=2; j<=Cols; j++)
     {
      app.Application.ActiveDocument.Tables.Item(TablesItem).Cell (beginRow + i,j).Select ();
      app.Application.Selection.Text=GetData(dt.Rows[xb][j-1].ToString());
     }
     xb++;
    }
    return true;
   }
   catch (System.Exception e)
   {
    doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);
    MessageBox(0,e.Message + "/r/n" + e.StackTrace ,"Error Message Box",0);
    return false;
   }
  }
  #endregion

  #region ******创建表格*******
  public bool CreateTable(int rownum,int colnum,string header)
  {
   try
   {
    char [] separtor1 = {';'};   
    char [] separtor2 = {','};
    string [] split1 = null;
    string [] split2 = null;
    split1 = header.Split(separtor1);
    Word.Table table=doc.Tables.Add(app.Selection.Range,rownum,colnum,ref optional,ref optional);
    for(int i=1; i<=split1.Length ;i++)
    {//添加每一行
     split2 = split1[i-1].Split(separtor2);
     for (int j=1; j<=split2.Length; j++)
     {//添加每一列
      table.Cell(i,j).Range.Text=split2[j-1].Trim();
     }
    }
    return true;
    
   }
   catch (System.Exception e)
   {
    doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);
    MessageBox(0,e.Message + "/r/n" + e.StackTrace ,"Error Message Box",0);
    return false;
   }
  }
  public bool ContentTableAdd(DataTable dt)
  {
   try
   {
    app.Selection.TypeParagraph();
    app.Selection.TypeParagraph();
    app.Selection.TypeParagraph();
    Word.Table table=doc.Tables.Add(app.Selection.Range,4,9,ref optional,ref optional);
    table.Cell(1,1).Range.Text=dt.Rows[0]["content_id"].ToString();
    return true;
    
   }
   catch (System.Exception e)
   {
    doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);
    MessageBox(0,e.Message + "/r/n" + e.StackTrace ,"Error Message Box",0);
    return false;
   }
  }
  #endregion

  #region ******删除表格*******
  public bool DelTable(int num)
  {
   try
   {
    doc.Tables.Item(num).Delete ();
    return true;
   }
   catch (System.Exception e)
   {
    doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);
    MessageBox(0,e.Message + "/r/n" + e.StackTrace ,"Error Message Box",0);
    return false;
   }
  }
  #endregion

  #region ******文件另存为*******
  public void SaveAs(ref object fileName)
  {
   try
   {
    doc.SaveAs(ref fileName,ref optional, ref optional, ref optional,ref optional, ref optional, ref optional,ref optional, ref optional, ref optional, ref optional);
   }
   catch (System.Exception e)
   {
    doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);
    throw new Exception (e.Message );
   }
  }
  #endregion

  #region ******关闭word*******
  public void Quit()
  {
   try
   {
    doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);
    app.Quit(ref NOTsaveChanges, ref originalFormat, ref routeDocument);
   }
   catch (System.Exception e)
   {
    throw new Exception (e.Message );
   }
  }
  public void AppQuit()
  {
   try
   {
    app.Quit(ref NOTsaveChanges, ref originalFormat, ref routeDocument);
   }
   catch (System.Exception e)
   {
    throw new Exception (e.Message );
   }
  }
  #endregion

  private object[] GetMark()
  { 
   object j=null;
   string str="";
   object []result=new object [doc.Bookmarks.Count];
   for (int i=1;i<=doc.Bookmarks.Count;i++)
   {
    j=(object)i;
    result[i-1]=doc.Bookmarks.Item(ref j).Name;
    str = str + doc.Bookmarks.Item(ref j).Name + ",";
   }
   return result;
  }

 }
}