c#操作word(二)[3]

[入库:2006年2月23日] [更新:2007年3月24日]

本文简介:

  #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

本文关键:c#操作word(二)
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top