文本是一個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(" ", " ");
//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(" ", " ");
str = str.Replace("\"", """);
str = str.Replace("\'", "'");
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(" ");
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);
