分享
 
 
 

c#操作word(二)

王朝c#·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

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

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

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有