c#操作word(二)

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

///

1<summary>   
2/// 打印商品   
3/// </summary>

///

1<param name="strUserName"/>

///

1<param name="strPackId"/>

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("

1<script language="javascript">window.open('");   
2Response.Write(strFileName);   
3Response.Write("')</script>

");

}
catch(Exception ex)
{
Response.Write("

1<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
{
///

1<summary>   
2/// EnDoc 的摘要说明。   
3/// </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

  1<lbl.length;i++ "长度不符"="" #endregion="" #region="" ());="" (e.message="" (ref="" (system.exception="" )="" );="" ******向表格写入数据*******="" ,"error="" <summary="" box",0);="" catch="" doc.close(ref="" e)="" else="" exception="" lbl[i],dt.rows[0][i].tostring="" message="" messagebox(0,="" new="" notsavechanges,="" originalformat,="" ref="" routedocument);="" throw="" writedata="" {="" }="">   
  2///   
  3///    
  4/// <param name="dt"/>DataTable   
  5/// <param name="beginRow"/>开始写入的起始行   
  6/// <param name="Cols"/>填充的列数   
  7/// <param name="TablesItem"/>表格在word中的序号,从1开始   
  8/// <returns></returns>   
  9public bool FillTable(DataTable dt,int beginRow,int Cols,int TablesItem)   
 10{   
 11try   
 12{   
 13object row =1;   
 14TablesItem=app.Application.ActiveDocument.Tables.Count;   
 15int xb=0;   
 16for (int i=0; i&lt;dt.Rows.Count; i++)   
 17{   
 18app.Application.ActiveDocument.Tables.Item(TablesItem).Cell (beginRow + i,1).Select ();   
 19app.Application.Selection.InsertRowsBelow (ref row);   
 20app.Application.Selection.Text=GetData(dt.Rows[xb][0].ToString());   
 21for (int j=2; j&lt;=Cols; j++)   
 22{   
 23app.Application.ActiveDocument.Tables.Item(TablesItem).Cell (beginRow + i,j).Select ();   
 24app.Application.Selection.Text=GetData(dt.Rows[xb][j-1].ToString());   
 25}   
 26xb++;   
 27}   
 28return true;   
 29}   
 30catch (System.Exception e)   
 31{   
 32doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);   
 33MessageBox(0,e.Message + "\r\n" + e.StackTrace ,"Error Message Box",0);   
 34return false;   
 35}   
 36}   
 37#endregion 
 38
 39#region ******创建表格*******   
 40public bool CreateTable(int rownum,int colnum,string header)   
 41{   
 42try   
 43{   
 44char [] separtor1 = {';'};   
 45char [] separtor2 = {','};   
 46string [] split1 = null;   
 47string [] split2 = null;   
 48split1 = header.Split(separtor1);   
 49Word.Table table=doc.Tables.Add(app.Selection.Range,rownum,colnum,ref optional,ref optional);   
 50for(int i=1; i&lt;=split1.Length ;i++)   
 51{//添加每一行   
 52split2 = split1[i-1].Split(separtor2);   
 53for (int j=1; j&lt;=split2.Length; j++)   
 54{//添加每一列   
 55table.Cell(i,j).Range.Text=split2[j-1].Trim();   
 56}   
 57}   
 58return true;   
 59  
 60}   
 61catch (System.Exception e)   
 62{   
 63doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);   
 64MessageBox(0,e.Message + "\r\n" + e.StackTrace ,"Error Message Box",0);   
 65return false;   
 66}   
 67}   
 68public bool ContentTableAdd(DataTable dt)   
 69{   
 70try   
 71{   
 72app.Selection.TypeParagraph();   
 73app.Selection.TypeParagraph();   
 74app.Selection.TypeParagraph();   
 75Word.Table table=doc.Tables.Add(app.Selection.Range,4,9,ref optional,ref optional);   
 76table.Cell(1,1).Range.Text=dt.Rows[0]["content_id"].ToString();   
 77return true;   
 78  
 79}   
 80catch (System.Exception e)   
 81{   
 82doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);   
 83MessageBox(0,e.Message + "\r\n" + e.StackTrace ,"Error Message Box",0);   
 84return false;   
 85}   
 86}   
 87#endregion 
 88
 89#region ******删除表格*******   
 90public bool DelTable(int num)   
 91{   
 92try   
 93{   
 94doc.Tables.Item(num).Delete ();   
 95return true;   
 96}   
 97catch (System.Exception e)   
 98{   
 99doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);   
100MessageBox(0,e.Message + "\r\n" + e.StackTrace ,"Error Message Box",0);   
101return false;   
102}   
103}   
104#endregion 
105
106#region ******文件另存为*******   
107public void SaveAs(ref object fileName)   
108{   
109try   
110{   
111doc.SaveAs(ref fileName,ref optional, ref optional, ref optional,ref optional, ref optional, ref optional,ref optional, ref optional, ref optional, ref optional);   
112}   
113catch (System.Exception e)   
114{   
115doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);   
116throw new Exception (e.Message );   
117}   
118}   
119#endregion 
120
121#region ******关闭word*******   
122public void Quit()   
123{   
124try   
125{   
126doc.Close(ref NOTsaveChanges, ref originalFormat, ref routeDocument);   
127app.Quit(ref NOTsaveChanges, ref originalFormat, ref routeDocument);   
128}   
129catch (System.Exception e)   
130{   
131throw new Exception (e.Message );   
132}   
133}   
134public void AppQuit()   
135{   
136try   
137{   
138app.Quit(ref NOTsaveChanges, ref originalFormat, ref routeDocument);   
139}   
140catch (System.Exception e)   
141{   
142throw new Exception (e.Message );   
143}   
144}   
145#endregion 
146
147private object[] GetMark()   
148{   
149object j=null;   
150string str="";   
151object []result=new object [doc.Bookmarks.Count];   
152for (int i=1;i&lt;=doc.Bookmarks.Count;i++)   
153{   
154j=(object)i;   
155result[i-1]=doc.Bookmarks.Item(ref j).Name;   
156str = str + doc.Bookmarks.Item(ref j).Name + ",";   
157}   
158return result;   
159} 
160
161}   
162}</lbl.length;i++>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus