c#操作word(二)

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

/// <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;
  }

 }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值