.net中操作word的方法集合

文本是一个Word文档中最简单的元素,通过各种形式的文本与其他元素有机组合才形成了一个完整的Word文档。本节介绍如何使用C#向Word文档中写入文本信息。
在向Word文档中写入文本时,仍然需要使用上节介绍的Microsoft Word X Object Library COM组件。写入文本的方法主要为设置MSWord.Document.Paragraphs.Last.Range.Text属性,通过设置不同的字符串,即可达到写入文本的目的。
1.目的说明
介绍如何向Word文档中写入文本和如何向Word文档中写入多行文本。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateWordXDemo。
(2)添加对Microsoft Word 12.0 Object Library的引用。
(3)在“Program.cs”文件中添加如下引用。
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
static void Main(string[] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量

path = @"C:\MyWord.docx"; //路径
wordApp = new MSWord.ApplicationClass(); //初始化
//如果已存在,则删除
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
strContent = "使用C#向Word文档中写入文本\n";
wordDoc.Paragraphs.Last.Range.Text = strContent;
strContent = "写入第二行文本";
wordDoc.Paragraphs.Last.Range.Text = strContent;
//WdSaveFormat为Word 2007文档的保存格式
object format =MSWord.WdSaveFormat.wdFormatDocumentDefault;
//将wordDoc文档对象的内容保存为DOCX文档
wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//关闭wordDoc文档对象
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
Console.WriteLine(path + " 创建完毕!");
}
}
3.运行结果
运行程序,结果如图8.9所示。

图8.9 运行结果
打开C盘根目录下的MyWord.docx,如图8.10所示。

图8.10 运行结果
8.3 使用C#向Word输出格式化的文本
一个Word文档不可能全部由无格式的普通文本组成,因此在从C#中向Word写入文本信息时经常要输出一些具有特殊字体、颜色的文本。本节介绍如何向Word输出格式化的文本。
Microsoft Word X Object Library COM组件中文本格式的设置主要是由文本所使用的字体决定的。该COM组件中可以直接设置C#中的Font类,使用非常方便。常用的格式属性有颜色、加粗、斜体、下画线等。
1.目的说明
分别介绍以下内容:
— 输出不同字体的文本。
— 输出不同颜色的文本。
— 输出带下画线的文本。
— 输出斜体文本。
— 输出加粗文本。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateFormatWordDemo。
(2)添加对Microsoft Word 12.0 Object Library的引用。
(3)在“Program.cs”文件中添加如下引用。
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
static void Main(string[] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量

path = @"C:\MyWord.docx"; //路径
wordApp = new MSWord.ApplicationClass(); //初始化
//如果已存在,则删除
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//写入普通文本
strContent = "普通文本普通文本普通文本普通文本普通文本\n";
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入黑体文本
strContent = "黑体文本黑体文本黑体文本黑体文本黑体文本\n";
wordDoc.Paragraphs.Last.Range.Font.Name = "黑体";
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入加粗文本
strContent = "加粗文本加粗文本加粗文本加粗文本加粗文本\n";
wordDoc.Paragraphs.Last.Range.Font.Bold = 1;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入15号字体文本
strContent = "15号字体文本15号字体文本15号字体文本15号字体文本\n";
wordDoc.Paragraphs.Last.Range.Font.Size = 15;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入斜体文本
strContent = "斜体文本斜体文本斜体文本斜体文本斜体文本\n";
wordDoc.Paragraphs.Last.Range.Font.Italic = 1;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入蓝色文本
strContent = "蓝色文本蓝色文本蓝色文本蓝色文本蓝色文本\n";
wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入下画线文本
strContent = "下画线文本下画线文本下画线文本下画线文本下画线文本\n";
wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入红色下画线文本
strContent = "红色下画线文本红色下画线文本红色下画线文本红色下画线文本\n";
wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick;
wordDoc.Paragraphs.Last.Range.Font.UnderlineColor = MSWord.WdColor.wdColorRed;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//WdSaveFormat为Word 2007文档的保存格式
object format =MSWord.WdSaveFormat.wdFormatDocumentDefault;
//将wordDoc文档对象的内容保存为DOCX文档
wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//关闭wordDoc文档对象
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
Console.WriteLine(path + " 创建完毕!");
}
}
3.运行结果
运行程序,结果如图8.11所示。
打开C盘根目录下的MyWord.docx,如图8.12所示。

图8.11 运行结果 图8.12 运行结果
8.4 使用C#向Word文档中添加表格
除了简单的文本信息外,Microsoft Word也是一个处理表格的强大工具。许多数据报表也需要通过表格的形式在Word中体现。本节将介绍如何使用C#在Word中创建一个表格。
表格是由Microsoft Word X Object Library中的MSWord.Table定义的,通过在Word文档中的Tables集合中添加一个Table对象,即可在Word文档中创建一个表格。该表格的行数和列数等属性都可以在Tables的Add方法中定义,表格的内容可由Cell属性访问。
1.目的说明
介绍如何向Word文档中输出表格和如何向Word文档中的表格填充文本。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateTableDemo。
(2)添加对Microsoft Word 12.0 Object Library的引用。
(3)在“Program.cs”文件中添加如下引用。
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
static void Main(string[] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量

path = @"C:\MyWord.docx"; //路径
wordApp = new MSWord.ApplicationClass(); //初始化
//如果已存在,则删除
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//定义一个Word中的表格对象
MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, 5, 5, ref Nothing, ref Nothing);
//默认创建的表格没有边框,这里修改其属性,使得创建的表格带有边框
table.Borders.Enable = 1;
//使用两层循环填充表格的内容
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
table.Cell(i,j).Range.Text = "第"+ i +"行,第"+ j +"列";
}
}
//WdSaveFormat为Word 2007文档的保存格式
object format =MSWord.WdSaveFormat.wdFormatDocumentDefault;
//将wordDoc文档对象的内容保存为DOCX文档
wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//关闭wordDoc文档对象
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
Console.WriteLine(path + " 创建完毕!");
}
}
3.运行结果
运行程序,结果如图8.13所示。
打开C盘根目录下的MyWord.docx,如图8.14所示。
分类: .net类

 

 

 

 

 


创建新Word
1 object oMissing = System.Reflection.Missing.Value;
2 Word._Application oWord;
3 Word._Document oDoc;
4 oWord = new Word.Application();
5 oWord.Visible = true;
6 oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
7 ref oMissing, ref oMissing);
8

打开文档:
1 object oMissing = System.Reflection.Missing.Value;
2 Word._Application oWord;
3 Word._Document oDoc;
4 oWord = new Word.Application();
5 oWord.Visible = true;
6 object fileName = @"E:CCCXCXXTestDoc.doc";
7 oDoc = oWord.Documents.Open(ref fileName,
8 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
9 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
10 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
11

导入模板
1 object oMissing = System.Reflection.Missing.Value;
2 Word._Application oWord;
3 Word._Document oDoc;
4 oWord = new Word.Application();
5 oWord.Visible = true;
6 object fileName = @"E:XXXCCXTest.doc";
7 oDoc = oWord.Documents.Add(ref fileName, ref oMissing,
8 ref oMissing, ref oMissing);
9

.添加新表
1 object oMissing = System.Reflection.Missing.Value;
2 Word._Application oWord;
3 Word._Document oDoc;
4 oWord = new Word.Application();
5 oWord.Visible = true;
6 oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
7 ref oMissing, ref oMissing);
8
9 object start = 0;
10 object end = 0;
11 Word.Range tableLocation = oDoc.Range(ref start, ref end);
12 oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);
13

.表插入行
1 object oMissing = System.Reflection.Missing.Value;
2 Word._Application oWord;
3 Word._Document oDoc;
4 oWord = new Word.Application();
5 oWord.Visible = true;
6 oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
7 ref oMissing, ref oMissing);
8
9 object start = 0;
10 object end = 0;
11 Word.Range tableLocation = oDoc.Range(ref start, ref end);
12 oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);
13
14 Word.Table newTable = oDoc.Tables[1];
15 object beforeRow = newTable.Rows[1];
16 newTable.Rows.Add(ref beforeRow);
17

.单元格合并
1 object oMissing = System.Reflection.Missing.Value;
2 Word._Application oWord;
3 Word._Document oDoc;
4 oWord = new Word.Application();
5 oWord.Visible = true;
6 oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
7 ref oMissing, ref oMissing);
8
9 object start = 0;
10 object end = 0;
11 Word.Range tableLocation = oDoc.Range(ref start, ref end);
12 oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);
13
14 Word.Table newTable = oDoc.Tables[1];
15 object beforeRow = newTable.Rows[1];
16 newTable.Rows.Add(ref beforeRow);
17
18 Word.Cell cell = newTable.Cell(1, 1);
19 cell.Merge(newTable.Cell(1, 2));
20

.单元格分离
1 object oMissing = System.Reflection.Missing.Value;
2 Word._Application oWord;
3 Word._Document oDoc;
4 oWord = new Word.Application();
5 oWord.Visible = true;
6 oDoc = oWord.Documents.Add( oMissing,
7 ref oMissing, ref oMissing);
8
9 object start = 0;
10 object end = 0;
11 Word.Range tableLocation = oDoc.Range(ref start, ref end);
12 oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);
13
14 Word.Table newTable = oDoc.Tables[1];
15 object beforeRow = newTable.Rows[1];
16 newTable.Rows.Add(ref beforeRow);
17
18 Word.Cell cell = newTable.Cell(1, 1);
19 cell.Merge(newTable.Cell(1, 2));
20
21 object Rownum = 2;
22 object Columnnum = 2;
23 cell.Split(ref Rownum, ref Columnnum);
24

通过段落控制插入
1 object oMissing = System.Reflection.Missing.Value;
2 object oEndOfDoc = "endofdoc"; /**//* endofdoc is a predefined bookmark */
3
4 //Start Word and create a new document.
5 Word._Application oWord;
6 Word._Document oDoc;
7 oWord = new Word.Application();
8 oWord.Visible = true;
9 oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
10 ref oMissing, ref oMissing);
11
12 //Insert a paragraph at the beginning of the document.
13 Word.Paragraph oPara1;
14 oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
15 oPara1.Range.Text = "Heading 1";
16 oPara1.Range.Font.Bold = 1;
17 oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph.
18 oPara1.Range.InsertParagraphAfter();

 

 

三、Webform1.aspx.cs代码
完成添加引用后,MSWORD.OLB已经转化为相关DLL文件并放置于项目的BIN目录下了,这样我们只需在源码中创建该对象,并使用word库文件内置的操作函数即可轻松实现操作Word,Webform1.aspx.cs源码如下:
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;
namespace word
{
/// <summary>
/// Webform1 的摘要说明。
/// </summary>
public class Webform1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox SaveAs;
protected System.Web.UI.WebControls.Button Button;
protected System.Web.UI.WebControls.Label Label2;
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Label result;
protected System.Web.UI.WebControls.TextBox wordText;
#region Web form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
public void Button_Click(object sender, System.EventArgs e)
{
Object Nothing=System.Reflection.Missing.value;
//取得Word文件保存路径
object filename=@SaveAs.Text;
//创建一个名为WordApp的组件对象
Word.Application WordApp=new Word.ApplicationClass();
//创建一个名为WordDoc的文档对象
Word.Document WordDoc=WordApp.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);
//增加一表格
Word.Table table=WordDoc.Tables.Add(WordApp.Selection.Range,1,1,ref Nothing,ref Nothing);
//在表格第一单元格中添加自定义的文字内容
table.Cell(1,1).Range.Text=wordText.Text;
//在文档空白地方添加文字内容
WordDoc.Paragraphs.Last.Range.Text="Wellcome To Aspxcn.Com";
//将WordDoc文档对象的内容保存为DOC文档
WordDoc.SaveAs(ref filename,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
//关闭WordDoc文档对象
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭WordApp组件对象
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
//返回结果
result.Text="文档路径:<a href="/"+SaveAs.Text+"'>"+SaveAs.Text+"</a>(点击链接查看)<br>生成结果:成功!";
}

private void Page_Load(object sender, System.EventArgs e)
{
}
}
}

 

四、Webform1.aspx代码

完成CS源码后,我们就可以设计Webform页面了,完整的代码如下:

<%@ Page language="c#" Codebehind="Webform1.aspx.cs" AutoEventWireup="false" Inherits="word.Webform1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>基于Webforms的操作Word</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="javascript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body ms_positioning="GridLayout">
<form id="form1" method="post" runat="server">
<FONT face="宋体">
<asp:TextBox id="wordText" style="Z-INDEX: 101; LEFT: 144px; POSITION: absolute; TOP: 129px" runat="server" Height="190px" Width="360px" TextMode="MultiLine"></asp:TextBox>
<asp:TextBox id="SaveAs" style="Z-INDEX: 102; LEFT: 143px; POSITION: absolute; TOP: 80px" runat="server" Width="360px">C:\myword.doc</asp:TextBox>
<asp:Button id="Button" style="Z-INDEX: 103; LEFT: 237px; POSITION: absolute; TOP: 340px" runat="server" Width="98px" on onClick="Button_Click" Text="生成Word文档"></asp:Button>
<INPUT style="Z-INDEX: 104; LEFT: 361px; WIDTH: 49px; POSITION: absolute; TOP: 340px; HEIGHT: 24px" type="reset" value="重填" size="20"></FONT>
<FONT face="宋体">基于Webforms的操作Word(小宝.NET)</FONT>
<asp:Label id="Label1" style="Z-INDEX: 105; LEFT: 143px; POSITION: absolute; TOP: 54px" runat="server" Width="187px" Height="18px">Word文件保存路径:</asp:Label>
<asp:Label id="Label2" style="Z-INDEX: 106; LEFT: 142px; POSITION: absolute; TOP: 107px" runat="server" Width="159px" Height="12px">Word文件内容:</asp:Label>
<asp:Label id="result" style="Z-INDEX: 107; LEFT: 148px; POSITION: absolute; TOP: 387px" runat="server" Width="352px" Height="18px" ForeColor="Red"></asp:Label>
</form>
</body>
</HTML>
五、web.config设置
web.config文件还需添加一句 <identity impersonate="true"/>以启用模拟身份,因为默认ASPNET这个用户是没有权限访问Word.ApplicationClass(),当启用模拟身份后所有页面将会使用匿名Internet用户帐户(IUSR_machinename)这个用户名的权限执行,这样我们就能成功访问Word.ApplicationClass()并在ASP.NET中操作Word!

VB.net:

Public Class WordClass
Public Function wirteWord(ByVal str As String, ByVal title As String) As Boolean
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Try
Dim obj As Object = System.Reflection.Missing.Value
'取得Word文件保存路径
Dim filename As Object = "C:\Inetpub\wwwroot\SLOA_NET\document\DocManage\" + title + ".doc"
'创建一个名为WordApp的组件对象
WordApp = New Word.ApplicationClass
'创建一个名为WordDoc的文档对象
WordDoc = WordApp.Documents.Add()
'在文档空白地方添加文字内容
WordDoc.Paragraphs.Last.Range.Text = str
'保存
WordDoc.SaveAs(filename)
'关闭WordDoc文档对象
WordDoc.Close()
'关闭WordApp组件对象
WordApp.Quit()
Return True
Catch ex As Exception
If Not WordDoc Is Nothing Then
WordDoc.Close()
End If
If Not WordApp Is Nothing Then
WordApp.Quit()
End If
Return False
End Try
End Function

Public Function readWord(ByVal title As String) As String
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Try
Dim obj As Object = System.Reflection.Missing.Value
Dim filename As Object = "C:\Inetpub\wwwroot\SLOA_NET\document\DocManage\" + title + ".doc"
WordApp = New Word.ApplicationClass
WordDoc = WordApp.Documents.Open(filename)
Dim comment As String = WordDoc.Range.Text
WordDoc.Close()
WordApp.Quit()
Return comment
Catch ex As Exception
If Not WordDoc Is Nothing Then
WordDoc.Close()
End If
If Not WordApp Is Nothing Then
WordApp.Quit()
End If
Return Nothing
End Try
End Function
Public Function printWord(ByVal title As String) As Boolean
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Try
Dim obj As Object = System.Reflection.Missing.Value
Dim filename As Object = "C:\Inetpub\wwwroot\SLOA_NET\document\DocManage\" + title + ".doc"
WordApp = New Word.ApplicationClass
WordDoc = WordApp.Documents.Open(filename)
WordApp.Visible = True
'WordApp.ActivePrinter = WordDoc.Range.Text

'WordDoc.Close()
'WordApp.Quit()
Return True
Catch ex As Exception
'If Not WordDoc Is Nothing Then
'WordDoc.Close()
'End If
'If Not WordApp Is Nothing Then
'WordApp.Quit()
'End If
'Return Nothing
End Try
Return False
End Function

Public Function printSetWord(ByVal title As String)
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Try
Dim obj As Object = System.Reflection.Missing.Value
Dim filename As Object = "C:\Inetpub\wwwroot\SLOA_NET\document\DocManage\" + title + ".doc"
WordApp = New Word.ApplicationClass
WordDoc = WordApp.Documents.Open(filename)
WordApp.Visible = True
WordApp.PrintPreview = True
'WordDoc.Close()
'WordApp.Quit()
Catch ex As Exception
'If Not WordDoc Is Nothing Then
'WordDoc.Close()
'End If
'If Not WordApp Is Nothing Then
'WordApp.Quit()
'End If
'Return Nothing
End Try
End Function

Public Function viewWord(ByVal title As String)
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Try
Dim obj As Object = System.Reflection.Missing.Value
Dim filename As Object = "C:\Inetpub\wwwroot\SLOA_NET\document\DocManage\" + title + ".doc"
WordApp = New Word.ApplicationClass
WordDoc = WordApp.Documents.Open(filename)
WordApp.Visible = True
WordApp.PrintPreview = True
Catch ex As Exception
If Not WordDoc Is Nothing Then
WordDoc.Close()
End If
If Not WordApp Is Nothing Then
WordApp.Quit()
End If
Return Nothing
End Try
End Function

End Class

 

 

 


#region 打开Word文档,并且返回对象wDoc,wDoc
/// <summary>
/// 打开Word文档,并且返回对象wDoc,wDoc
/// </summary>
/// <param name="FileName">完整Word文件路径+名称</param>
/// <param name="wDoc">返回的Word.Document wDoc对象</param>
/// <param name="WApp">返回的Word.Application对象</param>
public static void CreateWordDocument(string FileName,ref Word.Document wDoc,ref Word.Application WApp)
{
if(FileName == "") return;
Word.Document thisDocument = null;
Word.FormFields formFields = null;
Word.Application thisApplication = new Word.ApplicationClass();
thisApplication.Visible = true;
thisApplication.Caption = "";
thisApplication.Options.CheckSpellingAsYouType = false;
thisApplication.Options.CheckGrammarAsYouType = false;

Object filename = FileName;
Object ConfirmConversions = false;
Object ReadOnly = true;
Object AddToRecentFiles = false;

Object PasswordDocument = System.Type.Missing;
Object PasswordTemplate = System.Type.Missing;
Object Revert = System.Type.Missing;
Object WritePasswordDocument = System.Type.Missing;
Object WritePasswordTemplate = System.Type.Missing;
Object Format = System.Type.Missing;
Object Encoding = System.Type.Missing;
Object Visible = System.Type.Missing;
Object OpenAndRepair = System.Type.Missing;
Object DocumentDirection = System.Type.Missing;
Object NoEncodingDialog = System.Type.Missing;
Object XMLTransform = System.Type.Missing;

try
{
Word.Document wordDoc =
thisApplication.Documents.Open(ref filename, ref ConfirmConversions,
ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
ref Revert,ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection,
ref NoEncodingDialog, ref XMLTransform );

thisDocument = wordDoc;
wDoc = wordDoc;
WApp = thisApplication;
formFields = wordDoc.FormFields;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

}
#endregion

 

 

 


洋C#

公共类
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.Caching;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;

namespace MyITJob
{
public class Class1 : Code.DbHelper
{
SqlConnection conn;
SqlCommand comm = new SqlCommand();
StreamReader sr;
StreamWriter sw;

#region 打开数据库
/// <summary>
/// 打开数据库
/// </summary>

public void OpenConnection() {
CheckConnection();
}
public bool CheckConnection() {
if (conn.State == ConnectionState.Closed) {
try {
conn.ConnectionString = ConfigurationManager.ConnectionStrings["0745Job"].ConnectionString;
comm.Connection = conn;
conn.Open();
} catch {
return false;
}
}
return true;
}
#endregion

#region 关闭数据库
/// <summary>
/// 关闭当前数据库
/// </summary>
public void MyCloseConn() {
if (conn.State == ConnectionState.Open) {
conn.Close();
conn.Dispose();
comm.Dispose();
}
}
#endregion

#region 返回指定的sql语句的DataSet记录集(多用于绑定数据)
/// <summary>
/// 返回指定的sql语句的DataSet记录集(多用于绑定数据)
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public DataSet MyDataSet(string sql, string tablename) {
DataSet ds = new DataSet();
string sqlstr = ConfigurationManager.ConnectionStrings["0745Job"].ToString();
conn = new SqlConnection(sqlstr);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);

da.Fill(ds, tablename);
da.Dispose();
conn.Close();
conn.Dispose();
return ds;
}
#endregion

#region 返回指定的sql语句的DataSet记录集,是否开启缓存(多用于绑定数据)
/// <summary>
/// 返回指定的sql语句的DataSet记录集,是否开启缓存(多用于绑定数据)
/// </summary>
/// <param name="sql">SQL语句</param>
/// <param name="tablename">缓存表名,若开启缓存,则表名在程序结构中不得重复出现</param>
/// <param name="Sure">若开启缓存,则表名在程序结构中不得重复出现</param>
/// <returns></returns>
public DataSet MyDataSet(string sql, string tablename, bool Sure) {
DataSet CacheDataSet = new DataSet();
DataSet ds = new DataSet();
if (Sure) {
CacheDataSet = (DataSet)Cache[tablename];
if (CacheDataSet == null) {
string sqlstr = ConfigurationManager.ConnectionStrings["0745Job"].ToString();
conn = new SqlConnection(sqlstr);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds, tablename);
da.Dispose();
conn.Close();
conn.Dispose();
// 将结果集存到缓存中去。
CacheDataSet = ds;
Cache.Insert(tablename, ds, null, DateTime.Now.AddMinutes(1), Cache.NoSlidingExpiration);
} else {
ds = (DataSet)Cache[tablename];
}
} else {
return MyDataSet(sql, tablename);
}
return CacheDataSet;
}
#endregion

#region 删除所有缓存资源
/// <summary>
/// 删除所有缓存资源
/// </summary>
public static void RemoveAllCache() {
Cache _cache = HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
ArrayList _aList = new ArrayList();
while (CacheEnum.MoveNext()) {
_aList.Add(CacheEnum.Key);
}
foreach (string tempcache in _aList) {
_cache.Remove(tempcache);
}
}
#endregion

#region 执行SQL语句从而影响数据表内容(多用于添加、修改、删除语句)
/// <summary>
/// 执行SQL语句从而影响数据表内容(多用于添加、修改、删除语句)
/// </summary>
/// <param name="sql"></param>
public void MysqlExecute(string sql) {
try {
string sqlstr = ConfigurationManager.ConnectionStrings["0745Job"].ToString();
conn = new SqlConnection(sqlstr);
conn.Open();

comm = new SqlCommand(sql, conn);
comm.ExecuteNonQuery();
} catch (Exception e) {
throw new Exception(e.Message);
} finally {
MyCloseConn();
}
}
#endregion

#region 返回DataReader(多用于查询语句)
/// <summary>
/// 返回DataReader(多用于查询语句)
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public SqlDataReader MyDataReader(string sql) {
try {
string sqlstr = ConfigurationManager.ConnectionStrings["0745Job"].ToString();
conn = new SqlConnection(sqlstr);
conn.Open();

SqlCommand comm = new SqlCommand(sql, conn);
SqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection);

return dr;
} catch (Exception e) {
throw new Exception(e.Message);
}
}
#endregion

#region 加密Cookie
public string FormatCookie(string name) {
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
string agent = HttpContext.Current.Request.UserAgent;
string key = HttpContext.Current.Application["sitekey"].ToString();

string c_key = FormsAuthentication.HashPasswordForStoringInConfigFile(ip + agent + key + name, "MD5");
return c_key;
}
#endregion

#region 院校机构登陆,存入Cookie
public void SlCookie(string name) {
HttpCookie slCookie = new HttpCookie("slname");
slCookie["name"] = MyFormatstr(Server.UrlEncode(name));
slCookie["key"] = FormatCookie(name);
slCookie.Expires = DateTime.Now.AddMinutes(30);
Response.Cookies.Add(slCookie);
}
#endregion

#region 个人用户登录,存入Cookie
public void UserCookie(string name) {
HttpCookie userCookie = new HttpCookie("User");
if (HttpContext.Current.Request.Cookies["User"] != null) {
userCookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(userCookie);
}
userCookie["name"] = MyFormatstr(Server.UrlEncode(name));
userCookie["key"] = FormatCookie(name);
userCookie.Expires = DateTime.Now.AddMinutes(30);
HttpContext.Current.Response.Cookies.Add(userCookie);
}
#endregion

#region 企业用户登录,存入Cookie
public void qyCookie(string name) {
HttpCookie qyCookie = new HttpCookie("qyUser");
if (HttpContext.Current.Request.Cookies["qyUser"] != null) {
qyCookie.Expires = DateTime.Now.AddHours(-1);
HttpContext.Current.Response.Cookies.Add(qyCookie);
}
qyCookie["name"] = MyFormatstr(Server.UrlEncode(name));
qyCookie["key"] = FormatCookie(name);
qyCookie.Expires = DateTime.Now.AddMinutes(30);
HttpContext.Current.Response.Cookies.Add(qyCookie);
}
#endregion

#region 管理员用户登录,存入Cookie
public void AdminCookie(string name) {
HttpCookie AdminCookie = new HttpCookie("AdminUser");
AdminCookie["name"] = MyFormatstr(name);
AdminCookie["key"] = FormatCookie(name);
AdminCookie.Expires = DateTime.Now.AddMinutes(30);
Response.Cookies.Add(AdminCookie);
}
#endregion

#region 判断院校机构是否登录
/// <summary>
/// 判断院校机构是否登录
/// </summary>
public void MySlLogin() {
if(Request.Cookies["slname"] == null || (Request.Cookies["slname"].Values["key"] != FormatCookie(Server.UrlDecode(Request.Cookies["slname"].Values["name"])))) {
Response.Redirect("Default.aspx");
}
}
#endregion

#region 判断个人用户是否登录
/// <summary>
/// 判断个人用户是否登录
/// </summary>
public void MyUserLogin() {
if (Request.Cookies["User"] == null || (Request.Cookies["User"].Values["key"] != FormatCookie(Server.UrlDecode(Request.Cookies["User"].Values["name"])))) {
Response.Redirect("../Default.aspx", true);
}
}
#endregion

#region 判断企业用户是否登录
/// <summary>
/// 判断企业用户是否登录
/// </summary>
public void MyqyLogin() {
if (Request.Cookies["qyUser"] == null || (Request.Cookies["qyUser"].Values["key"] != FormatCookie(Server.UrlDecode(Request.Cookies["qyUser"].Values["name"])))) {
//Response.Write("<script>alert('登录超时,请重新登录!');window.location='../Default.aspx'</script>");
Response.Redirect("../Default.aspx", true);
}
}
#endregion

#region 判断管理员是否登录
/// <summary>
/// 判断管理员是否登录
/// </summary>
public void AdminLogin() {
if (Request.Cookies["AdminUser"] == null || (Request.Cookies["AdminUser"].Values["key"] != FormatCookie(Request.Cookies["AdminUser"].Values["name"]))) {
Response.Redirect("Admin_Login.aspx");
}
}
#endregion

#region 获取HTML的参数
/// <summary>
/// 获取HTML的参数
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public string q(string s) {
if (Request.QueryString[s] != null) {
return MyFormatstr(Request.QueryString[s].ToString());
}
return string.Empty;
}
#endregion

#region 定义文章标题字段长度
/// <summary>
/// 定义文章标题字段长度
/// </summary>
/// <param name="str">需要定义的文字内容</param>
/// <param name="maxstr">最大显示长度</param>
/// <param name="laststr">实际显示长度</param>
/// <returns>返回字符串 + "..."</returns>
public string FormatLeft(string str, int maxstr, int laststr) {
if (str.Length > maxstr) {
return str.Substring(0, laststr) + "...";
} else {
return str;
}
}
#endregion

#region 定义文章标题字段长度2
/// <summary>
/// 定义文章标题字段长度,无...符号
/// </summary>
/// <param name="str">需要定义的文字内容</param>
/// <param name="maxstr">最大显示长度</param>
/// <param name="laststr">实际显示长度</param>
/// <returns>返回字符串 + "..."</returns>
public string FormatLeft2(string str, int maxstr, int laststr) {
if (str.Length > maxstr) {
return str.Substring(0, laststr);
} else {
return str;
}
}
#endregion

#region 格式化文本(防止SQL注入)
/// <summary>
/// 格式化文本(防止SQL注入)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string MyFormatstr(string html) {
System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>]+\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
html = regex1.Replace(html, ""); //过滤<script></script>标记
html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
html = regex4.Replace(html, ""); //过滤iframe
html = regex5.Replace(html, ""); //过滤frameset
//html = regex6.Replace(html, ""); //过滤frameset
//html = regex7.Replace(html, ""); //过滤frameset
//html = regex8.Replace(html, ""); //过滤frameset
//html = regex9.Replace(html, "");
html = regex10.Replace(html, "s_elect");
html = regex11.Replace(html, "u_pudate");
html = regex12.Replace(html, "d_elete");
html = html.Replace("'", "’");
html = html.Replace("&nbsp;", " ");
//html = html.Replace("</strong>", "");
//html = html.Replace("<strong>", "");
return html;
}
#endregion

#region 格式化文本(输出内容)
/// <summary>
/// 格式化文本(输出内容)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string MyFormatDestr(string str) {
str = str.Replace(" ", " &nbsp;");
str = str.Replace("\"", "&quot;");
str = str.Replace("\'", "&#39;");
str = str.Replace("\n", "<br/> ");
str = str.Replace("\r\n", "<br/> ");
return str;
}
#endregion

#region 输出文本时不带html标签格式
public string MyFormatnoHtml(string str) {
//str = str.Replace("<p>", "");
Regex regex1 = new Regex(@"<p>",RegexOptions.IgnoreCase);
Regex regex2 = new Regex(@"</p>", RegexOptions.IgnoreCase);
Regex regex3 = new Regex(@"<br />", RegexOptions.IgnoreCase);

str = regex1.Replace(str, "");
str = regex2.Replace(str, "");
str = regex3.Replace(str, "");

return str;
}
#endregion

#region ListBox树形结构函数
public string Tab = "├";
public void MyListTree(int pid, string tbname, System.Web.UI.WebControls.ListBox mListBox) {
DataSet ds = new DataSet();

string sqlstr = ConfigurationManager.ConnectionStrings["0745Job"].ToString();
conn = new SqlConnection(sqlstr);

SqlDataAdapter da = new SqlDataAdapter("select * from " + tbname + " where Pid=" + pid + " order by OrderID desc, id asc", conn);
da.Fill(ds, "DDLtb");

for (int i = 0; i < ds.Tables["DDLtb"].Rows.Count; i++) {
mListBox.Items.Add(new ListItem(Tab + ds.Tables["DDLtb"].Rows[i][2].ToString(), ds.Tables["DDLtb"].Rows[i][0].ToString()));
Tab += "─┴";
MyListTree(int.Parse(ds.Tables["DDLtb"].Rows[i][0].ToString()), tbname, mListBox);
Tab = Tab.Substring(0, Tab.Length - 2);
}
}
#endregion

#region DropDownList树形结构函数
public string Tab1 = "";
public void MyListDDLTree(int pid, string tbname, System.Web.UI.WebControls.DropDownList mDDL) {
DataSet ds = new DataSet();

string sqlstr = ConfigurationManager.ConnectionStrings["0745Job"].ToString();
conn = new SqlConnection(sqlstr);

SqlDataAdapter da = new SqlDataAdapter("select * from " + tbname + " where Pid=" + pid, conn);
da.Fill(ds, "DDLtb1");

for (int i = 0; i < ds.Tables["DDLtb1"].Rows.Count; i++) {
mDDL.Items.Add(new ListItem(Tab1 + ds.Tables["DDLtb1"].Rows[i][2].ToString(), ds.Tables["DDLtb1"].Rows[i][0].ToString()));
Tab1 += Server.HtmlDecode("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
MyListDDLTree(int.Parse(ds.Tables["DDLtb1"].Rows[i][0].ToString()), tbname, mDDL);
Tab1 = Tab1.Substring(0, Tab1.Length - 8);
}
}
#endregion

#region TreeView树形结构
public void BindFreeViewhs(string sqlstr, System.Web.UI.WebControls.TreeView mTreeView) {
string Connstr = ConfigurationManager.ConnectionStrings["0745Job"].ToString();
conn = new SqlConnection(Connstr);

SqlDataAdapter da = new SqlDataAdapter(sqlstr, conn);
DataSet ds = new DataSet();
da.Fill(ds);

this.ViewState["ds"] = ds;
AddTree(0, (TreeNode)null, mTreeView);
}
//递归添加树的节点
public void AddTree(int pid, TreeNode pnode, System.Web.UI.WebControls.TreeView mTreeView) {
DataSet ds = (DataSet)this.ViewState["ds"];
DataView dvtree = new DataView(ds.Tables[0]);
//过滤pid,得到当前的所有子节点
dvtree.RowFilter = "[pid] = " + pid;

foreach (DataRowView row in dvtree) {
TreeNode node = new TreeNode();
if (pnode == null) { //添加根节点
node.Text = row["Article_Class_Name"].ToString();
mTreeView.Nodes.Add(node);
// 默认不展开节点
node.Expanded = false;
AddTree(Int32.Parse(row["id"].ToString()), node, mTreeView); //再次递归
} else { //添加当前节点的子节点
node.Text = row["Article_Class_Name"].ToString();
pnode.ChildNodes.Add(node);
// 默认不展开节点
node.Expanded = false;
AddTree(Int32.Parse(row["id"].ToString()), node, mTreeView); //再次递归
}
node.NavigateUrl = "/newsallid.aspx?pid=" + row["id"].ToString();
}
}
#endregion

#region 写入JS头设置文件
public void WriteJs(string JsUrl, string sAdZone) {
//用来读取ZoneSetting的值
string[] Arraydr;
//读取JS模板文件
string tempmappath = Server.MapPath(JsUrl);
if (File.Exists(tempmappath)) {
sr = new StreamReader(tempmappath);
string ssr = sr.ReadToEnd();
sr.Close();
//创建文件夹
//Directory.CreateDirectory(Server.MapPath("../AD/" + DateTime.Now.ToString("yyyyMM")));
//创建文件,根据ID(sAdZone)值读取ZoneType的值,并写入读取的JS模板
DataRow dr = MyDataSet("select * from [AdZone] where [id]='" + sAdZone + "'", "ZoneJsName").Tables[0].Rows[0];
sw = new StreamWriter(Server.MapPath("../AD/" + dr["ZoneJsName"].ToString()), false, System.Text.Encoding.GetEncoding("UTF-8"));
sw.WriteLine(ssr);
switch (Convert.ToInt32(dr["ZoneType"])) {
case 1:
sw.WriteLine("var ZoneAD_" + dr["id"].ToString() + " = new BannerZoneAD(" + "\"ZoneAD_" + dr["id"].ToString() + "\"" + ");");
sw.WriteLine("ZoneAD_" + dr["id"].ToString() + ".ZoneID = " + dr["id"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"].ToString() + ".ZoneWidth = " + dr["ZoneWidth"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"].ToString() + ".ZoneHeight = " + dr["ZoneHeight"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"].ToString() + ".ShowType = " + dr["ShowType"] + ";");
sw.WriteLine("");
ForWriteJS(dr["id"].ToString());
break;
case 2:
sw.WriteLine("var ZoneAD_" + dr["id"] + " = new PopZoneAD(" + "\"ZoneAD_" + dr["id"] + "\"" + ");");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneID = " + dr["id"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneWidth = " + dr["ZoneWidth"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneHeight = " + dr["ZoneHeight"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ShowType = " + dr["ShowType"] + ";");
Arraydr = dr["ZoneSetting"].ToString().Split(',');
sw.WriteLine("ZoneAD_" + dr["id"] + ".PopType = " + Arraydr[0].ToString() + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".Left = " + Arraydr[1].ToString() + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".Top = " + Arraydr[2].ToString() + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".CookieHour = 0;");
sw.WriteLine("");
ForWriteJS(dr["id"].ToString());
break;
case 3:
sw.WriteLine("var ZoneAD_" + dr["id"] + " = new MoveZoneAD(" + "\"ZoneAD_" + dr["id"] + "\"" + ");");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneID = " + dr["id"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneWidth = " + dr["ZoneWidth"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneHeight = " + dr["ZoneHeight"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ShowType = " + dr["ShowType"] + ";");
Arraydr = dr["ZoneSetting"].ToString().Split(',');
sw.WriteLine("ZoneAD_" + dr["id"] + ".Left = " + Arraydr[0].ToString() + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".Top = " + Arraydr[1].ToString() + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".Delta = " + Arraydr[2].ToString() + ";");
sw.WriteLine("");
ForWriteJS(dr["id"].ToString());
break;
case 4:
sw.WriteLine("var ZoneAD_" + dr["id"] + " = new FixedZoneAD(" + "\"ZoneAD_" + dr["id"] + "\"" + ");");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneID = " + dr["id"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneWidth = " + dr["ZoneWidth"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneHeight = " + dr["ZoneHeight"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ShowType = " + dr["ShowType"] + ";");
Arraydr = dr["ZoneSetting"].ToString().Split(',');
sw.WriteLine("ZoneAD_" + dr["id"] + ".Left = " + Arraydr[0].ToString() + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".Top = " + Arraydr[1].ToString() + ";");
sw.WriteLine("");
ForWriteJS(dr["id"].ToString());
break;
case 5:
sw.WriteLine("var ZoneAD_" + dr["id"] + " = new FloatZoneAD(" + "\"ZoneAD_" + dr["id"] + "\"" + ");");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneID = " + dr["id"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneWidth = " + dr["ZoneWidth"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ZoneHeight = " + dr["ZoneHeight"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".ShowType = " + dr["ShowType"] + ";");
Arraydr = dr["ZoneSetting"].ToString().Split(',');
sw.WriteLine("ZoneAD_" + dr["id"] + ".FloatType = " + Arraydr[0].ToString() + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".Left = " + Arraydr[1].ToString() + ";");
sw.WriteLine("ZoneAD_" + dr["id"] + ".Top = " + Arraydr[2].ToString() + ";");
sw.WriteLine("");
ForWriteJS(dr["id"].ToString());
break;
case 6:
sw.WriteLine("var ZoneAD_" + dr["id"].ToString() + " = new CodeZoneAD(" + "\"ZoneAD_" + dr["id"].ToString() + "\"" + ");");
sw.WriteLine("ZoneAD_" + dr["id"].ToString() + ".ZoneID = " + dr["id"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"].ToString() + ".ZoneWidth = " + dr["ZoneWidth"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"].ToString() + ".ZoneHeight = " + dr["ZoneHeight"] + ";");
sw.WriteLine("ZoneAD_" + dr["id"].ToString() + ".ShowType = " + dr["ShowType"] + ";");
sw.WriteLine("");
ForWriteJS(dr["id"].ToString());
break;
}
sw.WriteLine("ZoneAD_" + dr["id"] + ".Show();");
sw.Flush();
sw.Close();
} else {
Response.Write("<script>alert('未找到JS模板,请联系管理员');window.location='../Default.aspx'</script>");
}
}
#endregion

#region 取得数据集的总数,用以循环打印结果JS内容
public void ForWriteJS(string sAdZone) {
//取得数据集的总数,用以循环打印结果
DataTable dt = MyDataSet("select * from [Advertisement] where [ZoneID]='" + sAdZone + "' and Passed='√'", "ZoneJsName").Tables[0];
for (int j = 0; j < dt.Rows.Count; j++) {
sw.WriteLine("var objAD = new ObjectAD();");
sw.WriteLine("objAD.ADID = " + dt.Rows[j]["id"] + ";");
sw.WriteLine("objAD.ADType = " + dt.Rows[j]["ADType"] + ";");
sw.WriteLine("objAD.ADName = " + "\"" + dt.Rows[j]["ADName"] + "\"" + ";");
sw.WriteLine("objAD.ImgUrl = " + "\"" + dt.Rows[j]["ImgUrl"] + "\"" + ";");
sw.WriteLine("objAD.ImgWidth = " + dt.Rows[j]["ImgWidth"] + ";");
sw.WriteLine("objAD.ImgHeight = " + dt.Rows[j]["ImgHeight"] + ";");
sw.WriteLine("objAD.FlashWmode = " + dt.Rows[j]["FlashWmode"] + ";");
sw.WriteLine("objAD.ADIntro = " + "\"" + dt.Rows[j]["ADIntro"] + "\"" + ";");
sw.WriteLine("objAD.LinkUrl = " + "\"" + dt.Rows[j]["LinkUrl"] + "\"" + ";");
sw.WriteLine("objAD.LinkTarget = " + dt.Rows[j]["LinkTarget"] + ";");
sw.WriteLine("objAD.LinkAlt = " + "\"" + dt.Rows[j]["LinkAlt"] + "\"" + ";");
sw.WriteLine("objAD.Priority = " + dt.Rows[j]["Priority"] + ";");
sw.WriteLine("objAD.CountView = " + dt.Rows[j]["Views"] + ";");
sw.WriteLine("objAD.CountClick = " + dt.Rows[j]["Clicks"] + ";");
sw.WriteLine("objAD.InstallDir = " + "\"" + Application["PageTitle"].ToString() + "\"" + ";");
sw.WriteLine("objAD.ADDIR = " + "\"" + "AD" + "\"" + ";");
sw.WriteLine("ZoneAD_" + dt.Rows[j]["ZoneID"] + ".AddAD(objAD);");
sw.WriteLine("");
}
}
#endregion

#region 弹出JS窗口提示框
/// <summary>
/// 弹出JS窗口提示框
/// </summary>
/// <param name="message">提示消息</param>
/// <param name="url">URL地址,可选参数,为空则只弹出对话框,而不刷新页面</param>
public void JsWindows(string message, string url) {
if (url == "") {
HttpContext.Current.Response.Write("<script>alert('" + message + "')</script>");
} else {
HttpContext.Current.Response.Write("<script>alert('" + message + "');window.location='" + url + "'</script>");
}
}
#endregion

#region 弹出JS对话框并关闭当前页
public void JsWindowsAndClose(string message) {
Response.Write("<script>alert('" + message + "');window.close();</script>");
}
#endregion

#region 返回MD5加密数据
public string md5(string str) {
return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
}
#endregion

#region 越权操作提示框
/// <summary>
/// 越权操作提示框
/// </summary>
public void NoPurview() {
Response.Write("<script>alert('无权限,请确认您具备该权限。');window.location='Admin_Manage.aspx'</script>");
}
#endregion
}
}

分类: .net类
绿色通道: 好文要顶 关注我 收藏该文与我联系
洋C#
关注 - 0
粉丝 - 2 +加关注 0 0 (请您对文章做出评价) ? 博主前一篇:快速启动QQ聊天对话框

posted on 2012-01-31 14:55 洋C# 阅读(42) 评论(0) 编辑 收藏


刷新评论刷新页面返回顶部
发表评论
昵称:

评论内容: 上传图片

不改了 注销

[使用Ctrl+Enter键快速提交]

程序员问答社区,解决您的技术难题
博客园首页博问新闻闪存程序员招聘知识库

最新IT新闻:
· 诺基亚疯狂捞钱:再推万元Vertu奢华手机
· 霍洛维茨极品创业鸡汤 让创业者走出绝望
· 诺基亚中国员工的真情告白
· 三星将推第二代S Pen手写笔 支持语音
· Garat:与众不同的节电应用
? 更多新闻...
最新知识库文章:

· 编程高手与调试高手
· 我所信奉的编程哲学
· 心态和想法,是提高编程水平的关键
· 详图实证:再谈JavaScript的语源问题
· 还原JavaScript的真实历史

? 更多知识库文章...


China-Pub 低价书精选
China-Pub 计算机绝版图书按需印刷服务导航博客园 首页 新随笔 联系 订阅 管理 统计随笔 - 2 文章 - 105 评论 - 2 引用 - 0 公告昵称:洋C#
园龄:10个月
粉丝:2
关注:0
我的闪存

搜索

常用链接我的随笔我的评论我的参与最新评论我的标签我的标签随笔档案2011年11月 (1) 2011年10月 (1) 文章分类.net类(28) android(42) asp(1) java类(2) jquery(8) Linux(4) 架构(1) 其他(4) 设计模式(2) 数据库(8) 下载资源(2) 相册相册一 最新评论1. Re:C#有关HashTable的具体使用用法详解我今天正好学到这章--平凡的学习2. Re:快速启动QQ聊天对话框解释一下用法--平凡的学习阅读排行榜1. C#有关HashTable的具体使用用法详解(139)2. 快速启动QQ聊天对话框(31)评论排行榜1. 快速启动QQ聊天对话框(1)2. C#有关HashTable的具体使用用法详解(1)推荐排行榜Powered by:
博客园
Copyright ? 洋C#


Range.InsertFile方法
后来在网上又搜到了一种方法就是,将HTML内容保存到html文件中,然后使用
Range.InsertFile(filename,,,,)方法将HTML文件内容插入到WORD文档中。
相关资料: 《Insert html formatted text into word document asp.net(C#)》
代码如下:
app = new Microsoft.Office.Interop.Word.Application();
object filename = @"c:\my.doc";
doc = app.Documents.Open(ref filename, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
object mark = "content";
Bookmark bookmark = word.Bookmarks.get_Item(ref mark);
bookmark.Range.InsertFile(@"C:\test.html", ref missing, ref missing,
ref missing, ref missing);

posted on 2012-06-21 14:39  larryle  阅读(8319)  评论(1)    收藏  举报