总结
文本是一个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);
`````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Drawing;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
using System.Windows.Forms;
/************************************************************************************************************************************
* * 文件名 :
* * 声明 :
* * 创建者 : 黄聪
* * 创建日期 : 2009.10.8
* * 修改者 : 黄聪
* * 最新修改日期 : 2009.10.8
************************************************************************************************************************************/
namespace Tool
{
/********************************************************************************************************************************
* * 类名 : WordPlayer
* * 声明 :
* * 创建者 : 黄聪
* * 创建日期 : 2009.7.15
* * 修改者 : 黄聪
* * 最新修改日期 : 2009.7.15
********************************************************************************************************************************/
public class WordPlayer
{
#region - 属性 -
private static Microsoft.Office.Interop.Word._Application oWord = null;
private static Microsoft.Office.Interop.Word._Document odoc = null;
private static Microsoft.Office.Interop.Word._Document oDoc
{
get
{
if (odoc == null)
{
odoc = oWord.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
}
return odoc;
}
set
{
if (value != null)
{
odoc = value;
}
}
}
private static object Nothing = System.Reflection.Missing.Value;
public enum Orientation
{
横板,
竖板
}
public enum Alignment
{
左对齐,
居中,
右对齐
}
#endregion
#region - 添加文档 -
#region - 创建并打开一个空的word文档进行编辑 -
public static void OpenNewWordFileToEdit()
{
oDoc = oWord.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
}
#endregion
#endregion
#region - 创建新Word -
public static bool CreateWord(bool isVisible)
{
try
{
oWord = new Microsoft.Office.Interop.Word.Application();
oWord.Visible = isVisible;
return true;
}
catch (Exception)
{
return false;
}
}
public static bool CreateWord()
{
return CreateWord(false);
}
#endregion
#region - 打开文档 -
public static bool Open(string filePath, bool isVisible)
{
try
{
oWord.Visible = isVisible;
object path = filePath;
oDoc = oWord.Documents.Open(ref path,
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);
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 插入表格 -
public static bool InsertTable(DataTable dt, bool haveBorder, double[] colWidths)
{
try
{
object Nothing = System.Reflection.Missing.Value;
int lenght = oDoc.Characters.Count - 1;
object start = lenght;
object end = lenght;
//表格起始坐标
Microsoft.Office.Interop.Word.Range tableLocation = oDoc.Range(ref start, ref end);
//添加Word表格
Microsoft.Office.Interop.Word.Table table = oDoc.Tables.Add(tableLocation, dt.Rows.Count, dt.Columns.Count, ref Nothing, ref Nothing);
if (colWidths != null)
{
for (int i = 0; i < colWidths.Length; i++)
{
table.Columns[i + 1].Width = (float)(28.5F * colWidths[i]);
}
}
///设置TABLE的样式
table.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAtLeast;
table.Rows.Height = oWord.CentimetersToPoints(float.Parse("0.8"));
table.Range.Font.Size = 10.5F;
table.Range.Font.Name = "宋体";
table.Range.Font.Bold = 0;
table.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
table.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
if (haveBorder == true)
{
//设置外框样式
table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
//样式设置结束
}
for (int row = 0; row < dt.Rows.Count; row++)
{
for (int col = 0; col < dt.Columns.Count; col++)
{
table.Cell(row + 1, col + 1).Range.Text = dt.Rows[row][col].ToString();
}
}
return true;
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
finally
{
}
}
public static bool InsertTable(DataTable dt, bool haveBorder)
{
return InsertTable(dt, haveBorder, null);
}
public static bool InsertTable(DataTable dt)
{
return InsertTable(dt, false, null);
}
#endregion
#region - 插入文本 -
public static bool InsertText(string strText, System.Drawing.Font font, Alignment alignment, bool isAftre)
{
try
{
Word.Range rng = oDoc.Content;
int lenght = oDoc.Characters.Count - 1;
object start = lenght;
object end = lenght;
rng = oDoc.Range(ref start, ref end);
if (isAftre == true)
{
strText += "\r\n";
}
rng.Text = strText;
rng.Font.Name = font.Name;
rng.Font.Size = font.Size;
if (font.Style == FontStyle.Bold) { rng.Font.Bold = 1; } //设置单元格中字体为粗体
SetAlignment(rng, alignment);
return true;
}
catch (Exception)
{
return false;
}
}
public static bool InsertText(string strText)
{
return InsertText(strText, new System.Drawing.Font("宋体", 10.5F, FontStyle.Bold), Alignment.左对齐, false);
}
#endregion
#region - 设置对齐方式 -
private static Microsoft.Office.Interop.Word.WdParagraphAlignment SetAlignment(Range rng, Alignment alignment)
{
rng.ParagraphFormat.Alignment = SetAlignment(alignment);
return SetAlignment(alignment);
}
private static Microsoft.Office.Interop.Word.WdParagraphAlignment SetAlignment(Alignment alignment)
{
if (alignment == Alignment.居中)
{
return Word.WdParagraphAlignment.wdAlignParagraphCenter;
}
else if (alignment == Alignment.左对齐)
{
return Word.WdParagraphAlignment.wdAlignParagraphLeft;
}
else
{ return Word.WdParagraphAlignment.wdAlignParagraphRight; }
}
#endregion
#region - 页面设置 -
public static void SetPage(Orientation orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
oDoc.PageSetup.PageWidth = oWord.CentimetersToPoints((float)width);
oDoc.PageSetup.PageHeight = oWord.CentimetersToPoints((float)height);
if (orientation == Orientation.横板)
{
oDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
}
oDoc.PageSetup.TopMargin = (float)(topMargin * 25);//上边距
oDoc.PageSetup.LeftMargin = (float)(leftMargin * 25);//左边距
oDoc.PageSetup.RightMargin = (float)(rightMargin * 25);//右边距
oDoc.PageSetup.BottomMargin = (float)(bottomMargin * 25);//下边距
}
public static void SetPage(Orientation orientation, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
SetPage(orientation, 21, 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
}
public static void SetPage(double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
SetPage(Orientation.竖板, 21, 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
}
#endregion
#region - 插入分页符 -
public static void InsertBreak()
{
Word.Paragraph para;
para = oDoc.Content.Paragraphs.Add(ref Nothing);
object pBreak = (int)WdBreakType.wdSectionBreakNextPage;
para.Range.InsertBreak(ref pBreak);
}
#endregion
#region - 关闭当前文档 -
public static bool CloseDocument()
{
try
{
object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
oDoc.Close(ref doNotSaveChanges, ref Nothing, ref Nothing);
oDoc = null;
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 关闭程序 -
public static bool Quit()
{
try
{
object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
oWord.Quit(ref saveOption, ref Nothing, ref Nothing);
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 保存文档 -
public static bool Save(string savePath)
{
return Save(savePath, false);
}
public static bool Save(string savePath, bool isClose)
{
try
{
object fileName = savePath;
oDoc.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);
if (isClose)
{
return CloseDocument();
}
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 插入页脚 -
public static bool InsertPageFooter(string text, System.Drawing.Font font, WordPlayer.Alignment alignment)
{
try
{
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;//页脚
oWord.Selection.InsertAfter(text);
GetWordFont(oWord.Selection.Font, font);
SetAlignment(oWord.Selection.Range, alignment);
return true;
}
catch (Exception)
{
return false;
}
}
public static bool InsertPageFooterNumber(System.Drawing.Font font, WordPlayer.Alignment alignment)
{
try
{
oWord.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
oWord.Selection.WholeStory();
oWord.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;//页脚
oWord.Selection.TypeText("第");
object page = WdFieldType.wdFieldPage;
oWord.Selection.Fields.Add(oWord.Selection.Range, ref page, ref Nothing, ref Nothing);
oWord.Selection.TypeText("页/共");
object pages = WdFieldType.wdFieldNumPages;
oWord.Selection.Fields.Add(oWord.Selection.Range, ref pages, ref Nothing, ref Nothing);
oWord.Selection.TypeText("页");
GetWordFont(oWord.Selection.Font, font);
SetAlignment(oWord.Selection.Range, alignment);
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 字体格式设定 -
public static void GetWordFont(Microsoft.Office.Interop.Word.Font wordFont, System.Drawing.Font font)
{
wordFont.Name = font.Name;
wordFont.Size = font.Size;
if (font.Bold) { wordFont.Bold = 1; }
if (font.Italic) { wordFont.Italic = 1; }
if (font.Underline == true)
{
wordFont.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
}
wordFont.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
if (font.Strikeout)
{
wordFont.StrikeThrough = 1;//删除线
}
}
#endregion
#region - 获取Word中的颜色 -
public static WdColor GetWordColor(Color c)
{
UInt32 R = 0x1, G = 0x100, B = 0x10000;
return (Microsoft.Office.Interop.Word.WdColor)(R * c.R + G * c.G + B * c.B);
}
#endregion
}
}
新建一个窗体工程,拖入一个按钮,复制下面代码进去,按F5运行
private void button2_Click(object sender, EventArgs e)
{
if (WordPlayer.CreateWord() == false)
{
MessageBox.Show("文件创造失败.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DataTable storedt = new DataTable();
storedt.Columns.Add("Book_ISBN");
storedt.Columns.Add("Book_Name");
storedt.Columns.Add("Store_Num");
storedt.Columns.Add("CanBorrow_Num");
storedt.Columns.Add("InShop_Num");
storedt.Columns.Add("OutShop_Num");
storedt.Rows.Add("1", "1", "1", "1", "1", "1");
storedt.Rows.Add("2", "2", "2", "2", "2", "2");
storedt.Rows.Add("3", "3", "3", "3", "3", "3");
storedt.Rows.Add("4", "4", "4", "4", "4", "4");
storedt.Rows.Add("5", "5", "5", "5", "5", "5");
storedt.Rows.Add("6", "6", "6", "6", "6", "6");
WordPlayer.SetPage(WordPlayer.Orientation.横板, 18.4, 26, 3, 2.4, 1.87, 2.1);
WordPlayer.InsertText("工 资 变 动 情 况 审 批 表", new Font("微软雅黑", 14, FontStyle.Bold), WordPlayer.Alignment.居中, true);
WordPlayer.InsertText("", new Font("微软雅黑", 14, FontStyle.Bold), WordPlayer.Alignment.居中, true);
WordPlayer.InsertText("姓名:A 审批单位:广西师范大学",
new Font("宋体", 12, FontStyle.Regular), WordPlayer.Alignment.左对齐, false);
WordPlayer.InsertTable(storedt, true);
WordPlayer.InsertText("制表时间:2007年1月15日", new Font("宋体", 12, FontStyle.Regular), WordPlayer.Alignment.右对齐, false);
WordPlayer.Save(Application.StartupPath + "\\test.doc",true);
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>始终居中的弹出层</title>
<style type="text/css">
<!--
html,body {height:100%; margin:0px; font-size:12px;}
.mydiv {
background-color: #FFCC66;
border: 1px solid #f00;
text-align: center;
line-height: 40px;
font-size: 12px;
font-weight: bold;
z-index:999;
width: 300px;
height: 120px;
left:50%;
top:50%;
margin-left:-150px!important;/*FF IE7 该值为本身宽的一半 */
margin-top:-60px!important;/*FF IE7 该值为本身高的一半*/
margin-top:0px;
position:fixed!important;/* FF IE7*/
position:absolute;/*IE6*/
_top: expression(eval(document.compatMode &&
document.compatMode=='CSS1Compat') ?
documentElement.scrollTop + (document.documentElement.clientHeight-this.offsetHeight)/2 :/*IE6*/
document.body.scrollTop + (document.body.clientHeight - this.clientHeight)/2);/*IE5 IE5.5*/
}
.bg,.popIframe {
background-color: #666; display:none;
width: 100%;
height: 100%;
left:0;
top:0;/*FF IE7*/
filter:alpha(opacity=50);/*IE*/
opacity:0.5;/*FF*/
z-index:1;
position:fixed!important;/*FF IE7*/
position:absolute;/*IE6*/
_top: expression(eval(document.compatMode &&
document.compatMode=='CSS1Compat') ?
documentElement.scrollTop + (document.documentElement.clientHeight-this.offsetHeight)/2 :/*IE6*/
document.body.scrollTop + (document.body.clientHeight - this.clientHeight)/2);
}
.popIframe {
filter:alpha(opacity=0);/*IE*/
opacity:0;/*FF*/
}
-->
</style>
<script language="javascript" type="text/javascript">
function showDiv(){
document.getElementById('popDiv').style.display='block';
document.getElementById('popIframe').style.display='block';
document.getElementById('bg').style.display='block';
}
function closeDiv(){
document.getElementById('popDiv').style.display='none';
document.getElementById('bg').style.display='none';
document.getElementById('popIframe').style.display='none';
}
</script>
</head>
<body>
<div id="popDiv" class="mydiv" style="display:none;">网页设计大本营欢迎你!<br/>Q群号:29032448<br/>
<a href="javascript:closeDiv()">关闭窗口</a></div>
<div id="bg" class="bg" style="display:none;"></div>
<a href="javascript:showDiv()">点击这里弹出层</a>
<iframe id='popIframe' class='popIframe' frameborder='0' ></iframe>
</body>
</html>
要使用C#操作word,首先要添加引用:
1、添加引用->COM->Microsoft Word 11.0 Object Library
2、在.cs文件中添加
using Word;
下面的例子中包括C#对Word文档的创建、插入表格、设置样式等操作:
(例子中代码有些涉及数据信息部分被省略,重要是介绍一些C#操作word文档的方法)
public string CreateWordFile(string CheckedInfo)
…{
string message = “”;
try
…{
Object Nothing = System.Reflection.Missing.Value;
Directory.CreateDirectory(“C:/CNSI”); //创建文件所在目录
string name = “CNSI_” + DateTime.Now.ToShortString()+”.doc”;
object filename = “C://CNSI//” + name; //文件保存路径
//创建Word文档
Word.Application WordApp = new Word.ApplicationClass();
Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//添加页眉
WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter(“[页眉内容]“);
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置
WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距
//移动焦点并换行
object count = 14;
object WdLine = Word.WdUnits.wdLine;//换一行;
WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点
WordApp.Selection.TypeParagraph();//插入段落
//文档中创建表格
Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing);
//设置表格样式
newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;
newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
newTable.Columns[1].Width = 100f;
newTable.Columns[2].Width = 220f;
newTable.Columns[3].Width = 105f;
//填充表格内容
newTable.Cell(1, 1).Range.Text = “产品详细信息表”;
newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体
//合并单元格
newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
//填充表格内容
newTable.Cell(2, 1).Range.Text = “产品基本信息”;
newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
//合并单元格
newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
//填充表格内容
newTable.Cell(3, 1).Range.Text = “品牌名称:”;
newTable.Cell(3, 2).Range.Text = BrandName;
//纵向合并单元格
newTable.Cell(3, 3).Select();//选中一行
object moveUnit = Word.WdUnits.wdLine;
object moveCount = 5;
object moveExtend = Word.WdMovementType.wdExtend;
WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
WordApp.Selection.Cells.Merge();
//插入图片
string FileName = Picture;//图片所在路径
object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = WordDoc.Application.Selection.Range;
WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度
WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
//将图片设置为四周环绕型
Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;
newTable.Cell(12, 1).Range.Text = “产品特殊属性”;
newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
//在表格中增加行
WordDoc.Content.Tables[1].Rows.Add(ref Nothing);
WordDoc.Paragraphs.Last.Range.Text = “文档创建时间:” + DateTime.Now.ToString();//“落款”
WordDoc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
//文件保存
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.Close(ref Nothing, ref Nothing, ref Nothing);
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
message=name+”文档生成成功,以保存到C:CNSI下”;
}
catch
…{
message = “文件导出异常!”;
}
return message;
}
=====================
输入标题:在当前光标处插入一段文字并设置成Heading 1样式,居中
相应的C#代码:
//因为set_Style()要求传ref object参数,所以不能直接传string
object style_Heading1 = ”Heading 1″;
WordApp = new ApplicationClass();
WordApp.Selection.TypeText(“Test Title”);
//设置样式
WordApp.Selection.ParagraphFormat.set_Style(ref style_Heading1);
//居中
WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
//换行
WordApp.Selection.TypeParagraph();
插入一个三行两列的表格,在第一行第一列填入今天的日期,设置样式,根据内容自动调整,去掉标题行
C#:注意最后需要调用WordApp.Selection.EndKey把光标移到表格之后,否则在插入表格后光标还在表格之前
WordDoc = WordApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing);
//表格要使用的样式
object style_Table1 = ”Medium Shading 1 - Accent 1″;
object wdStory = WdUnits.wdStory;
//添加表格
Table table = WordDoc.Tables.Add(WordApp.Selection.Range, 3, 2, ref nothing, ref nothing);
//设置样式
table.set_Style(ref style_Table1);
//去掉标题行
table.ApplyStyleHeadingRows = false;
//在第一行第一列插入日期
//注意:word中表格的行列起始下标都是1
table.Cell(1, 1).Range.Text = DateTime.Today.ToShortDateString();
//根据内容自动调整
table.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitContent);
//将光标移到表格后
WordApp.Selection.EndKey(ref wdStory, ref nothing);
在纵向页面中插入一个横向的页面
去掉冗余代码,C#很简单:
object sectionBreak = WdBreakType.wdSectionBreakNextPage;
//插入分节符
WordApp.Selection.InsertBreak(ref sectionBreak);
//将当前页面调整为横向
WordApp.Selection.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
//再插入分节符
WordApp.Selection.InsertBreak(ref sectionBreak);
//将当前页面调整为纵向
WordApp.Selection.PageSetup.Orientation = WdOrientation.wdOrientPortrait;
设置项目符号(默认)及自定义的编号(Hello 1, Hello 2,……)
//应用默认项目符号
WordApp.Selection.Range.ListFormat.ApplyBulletDefault(ref nothing);
WordApp.Selection.TypeText(“A1″);
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeText(“A2″);
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeText(“A3″);
WordApp.Selection.TypeParagraph();
//使用完记得取消掉
WordApp.Selection.Range.ListFormat.ApplyBulletDefault(ref nothing);
//应用编号
WordApp.Selection.Range.ListFormat.ApplyNumberDefault(ref nothing);
//自定义格式
WordApp.Selection.Range.ListFormat.ListTemplate.ListLevels[1].NumberFormat = ”Hello %1:”;
WordApp.Selection.TypeText(“B1″);
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeText(“B2″);
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeText(“B3″);
WordApp.Selection.TypeParagraph();
//取消编号
WordApp.Selection.Range.ListFormat.ApplyNumberDefault(ref
how to backup and strore myslq data base in c# application
- i wrote backup and restore
//backup
string s = "--host=192.168.0.100 --user=nhat --password=nhat DATDB -r \"" + string.Format("{0}", @"C:\DATDB.sql") + "\"";
Process.Start(@"c:\mysqldump.exe",s );
//restore
string s = "--host=192.168.0.100 --user=nhat --password=nhat DATDB < \"" + string.Format("{0}", @"C:\DATDB.sql") + "\"";
Process.Start(@"c:\mysql.exe", s);
通过调用MySql的工具mysqldump来实现。
类Cmd来实现调用cmd命令,
要启动的进程所在的目录是说mysql自动的备份还原数据库工具mysqldump和mysql所在目录,当然,这个方法可以执行别的命令行工具。
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
public class Cmd
{
/// <summary>
/// 执行Cmd命令
/// </summary>
/// <param name="workingDirectory">要启动的进程的目录</param>
/// <param name="command">要执行的命令</param>
public static void StartCmd(String workingDirectory, String command)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.WorkingDirectory = workingDirectory;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine(command);
p.StandardInput.WriteLine("exit");
}
}
备份方法:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Configuration;
using MDRClient.DataAccess;
namespace MDRClient
{
public partial class DataBackup : Form
{
public DataBackup()
{
InitializeComponent();
}
private void btnBackup_Click(object sender, EventArgs e)
{
try
{
//String command = "mysqldump --quick --host=localhost --default-character-set=gb2312 --lock-tables --verbose --force --port=端口号 --user=用户名 --password=密码 数据库名 -r 备份到的地址";
//构建执行的命令
StringBuilder sbcommand = new StringBuilder();
StringBuilder sbfileName = new StringBuilder();
sbfileName.AppendFormat("{0}", DateTime.Now.ToString()).Replace("-", "").Replace(":", "").Replace(" ", "");
String fileName = sbfileName.ToString();
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.AddExtension = false;
saveFileDialog.CheckFileExists = false;
saveFileDialog.CheckPathExists = false;
saveFileDialog.FileName = fileName;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
String directory = saveFileDialog.FileName;
sbcommand.AppendFormat("mysqldump --quick --host=localhost --default-character-set=gbk --lock-tables --verbose --force --port=端口号 --user=用户名 --password=密码 数据库名 -r \"{0}\"", directory);
String command = sbcommand.ToString();
//获取mysqldump.exe所在路径
String appDirecroty = System.Windows.Forms.Application.StartupPath + "\\";
Cmd.StartCmd(appDirecroty, command);
MessageBox.Show(@"数据库已成功备份到 " + directory + " 文件中", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("数据库备份失败!");
}
}
}
}
还原方法,调用的是mysql自带工具mysql,还原时要注意的是选择的文件所在路径时,文件名要是有空格的话会出
异常,所以在文件路径名加上双引号""
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Configuration;
using MDRClient.DataAccess;
namespace MDRClient
{
public partial class DataRestore : Form
{
public DataRestore()
{
InitializeComponent();
}
private void btnRestore_Click(object sender, EventArgs e)
{
//string s = "mysql --port=端口号 --user=用户名 --password=密码 数据库名<还原文件所在路径";
try
{
StringBuilder sbcommand = new StringBuilder();
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
String directory = openFileDialog.FileName;
//在文件路径后面加上""避免空格出现异常
sbcommand.AppendFormat("mysql --host=localhost --default-character-set=gbk --port=端口号 --user=用户名 --password=密码 数据库<\"{0}\"", directory);
String command = sbcommand.ToString();
//获取mysql.exe所在路径
String appDirecroty = System.Windows.Forms.Application.StartupPath + "\\";
DialogResult result = MessageBox.Show("您是否真的想覆盖以前的数据库吗?那么以前的数据库数据将丢失!!!", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
Cmd.StartCmd(appDirecroty, command);
MessageBox.Show("数据库还原成功!");
}
}
}
catch (Exception ex)
{
MessageBox.Show("数据库还原失败!");
}
}
}
}
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
CREATE PROCEDURE `P_viewPage`(
$TableName VARCHAR(200),
$FieldList VARCHAR(2000),
$PrimaryKey VARCHAR(100),
$Where VARCHAR(1000),
$Order VARCHAR(1000),
$SortType INT,
$RecorderCount INT,
$PageSize INT,
$PageIndex INT,
OUT $TotalCount INTEGER,
OUT $TotalPageCount INTEGER
)
BEGIN
IF !(($TableName is null OR $TableName='') OR ($FieldList is null OR $FieldList='') OR ($PrimaryKey is null OR $PrimaryKey='') OR $SortType < 1 OR $SortType >3 OR $RecorderCount < 0 OR $PageSize < 0 OR $PageIndex < 0) THEN
IF ($where is null OR $where='') THEN
SET @new_where1 = ' ' ;
SET @new_where2 = ' WHERE ' ;
ELSE
SET @new_where1 =concat(' WHERE ',$where);
SET @new_where2 =concat(' WHERE ',$where,' AND ');
END IF;
IF $order='' OR $SortType = 1 OR $SortType = 2 THEN
IF $SortType = 1 THEN
SET @new_order =concat(' ORDER BY ',$PrimaryKey,' ASC' );
END IF;
IF $SortType = 2 THEN
SET @new_order =concat(' ORDER BY ',$PrimaryKey,' DESC');
END IF;
ELSE
SET @new_order =concat(' ORDER BY ',$Order);
END IF;
SET @SqlCount = concat('SELECT COUNT(*) into @TotalCount FROM ',$TableName,@new_where1);
SET @SqlCount1 = concat('SELECT CEILING((COUNT(*)+0.0)/',$PageSize,') into @TotalPageCount FROM ',$TableName,@new_where1);
IF $RecorderCount = 0 THEN
PREPARE stmt1 FROM @SqlCount;
EXECUTE stmt1;
set $TotalCount=@TotalCount;
PREPARE stmt1 FROM @SqlCount1;
EXECUTE stmt1;
set $TotalPageCount=@TotalPageCount;
ELSE
set $TotalCount = $RecorderCount;
END IF;
IF $PageIndex > CEILING(($TotalCount+0.0)/$PageSize) THEN
SET $PageIndex = CEILING(($TotalCount+0.0)/$PageSize);
END IF;
IF $PageIndex = 0 or $PageIndex = 1 THEN
SET @Sql=concat('SELECT ',$FieldList,' FROM ',$TableName,@new_where1,@new_order,' limit ',$PageSize);
ELSE
IF $SortType = 1 THEN
SET @Sql=concat('SELECT ',$FieldList,' FROM ',$TableName,@new_where2,$PrimaryKey,' > (SELECT max(',$PrimaryKey,') FROM (SELECT ',$PrimaryKey,' FROM ',$TableName,@new_where1,@new_order,' limit ',$PageSize*($PageIndex-1),' ) AS TMP) ',@new_order,' limit ',$PageSize);
END IF;
IF $SortType = 2 THEN
SET @Sql=concat('SELECT ',$FieldList,' FROM ',$TableName,@new_where2,$PrimaryKey,' < (SELECT MIN(',$PrimaryKey,') FROM (SELECT ',$PrimaryKey,' FROM ',$TableName,@new_where1,@new_order,' limit ',$PageSize*($PageIndex-1),' ) AS TMP) ',@new_order,' limit ',$PageSize);
END IF;
IF $SortType = 3 THEN
IF INSTR($Order,',') > 0 THEN
SET @Sql=concat('SELECT ',$FieldList,' FROM ',$TableName,@new_where2,$PrimaryKey,' NOT IN (SELECT ',$PrimaryKey,' FROM (SELECT ',$PrimaryKey,' FROM ',$TableName,@new_where1,@new_order,' limit ',$PageSize*($PageIndex-1),' ) a)',@new_order,' limit ',$PageSize);
ELSE
SET @new_order =concat(' ORDER BY ',$PrimaryKey,' ASC' );
SET @Sql=concat('SELECT ',$FieldList,' FROM ',$TableName,@new_where2,$PrimaryKey,' > (SELECT max(',$PrimaryKey,') FROM (SELECT ',$PrimaryKey,' FROM ',$TableName,@new_where1,@new_order,' limit ',$PageSize*($PageIndex-1),' ) AS TMP) ',@new_order,' limit ',$PageSize);
END IF;
END IF;
END IF;
Prepare stmt2 from @Sql;
execute stmt2;
END IF;
END ;
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
存储过程分页的基本原理:我们先对查找到的记录集(支持输入查找条件_WhereClause和排列条件_OrderBy)的key字段临时存放到临时表,然后构建真正的记录集输出。
CREATE PROCEDURE `mysqltestuser_SELECT_PageAble`(
_WhereClause VARCHAR(2000), -- 查找条件
_OrderBy VARCHAR(2000), -- 排序条件
_PageSize INT , -- 每页记录数
_PageIndex INT , -- 当前页码
_DoCount BIT -- 标志:统计数据/输出数据
)
NOT DETERMINISTIC
SQL SECURITY DEFINER
COMMENT ' '
BEGIN
-- 定义key字段临时表
DROP TABLE IF EXISTS _TempTable_KeyID; -- 删除临时表,如果存在
CREATE TEMPORARY TABLE _TempTable_KeyID
(
userid INT
)TYPE=HEAP;
-- 构建动态的sql,输出关键字key的id集合
-- 查找条件
SET @sql = 'SELECT userid FROM mysqltestuser ';
IF (_WhereClause is NOT NULL) AND (_WhereClause <> ' ') THEN
SET @sql= concat(@sql, ' WHERE ' ,_WhereClause);
END if;
IF (_OrderBy is NOT NULL) AND (_OrderBy <> ' ') THEN
SET @sql= concat( @sql , ' ORDER BY ' , _OrderBy);
END IF;
-- 准备id记录插入到临时表
set @sql=concat( 'insert into _TempTable_KeyID(userid) ', @sql);
PREPARE stmt FROM @sql;
EXECUTE stmt ;
DEALLOCATE PREPARE stmt;
-- key的id集合 [end]
-- 下面是输出
IF (_DoCount=1) then -- 统计
BEGIN
SELECT COUNT(*) AS RecordCount FROM _TempTable_KeyID;
END;
ELSE -- 输出记录集
BEGIN
-- 计算记录的起点位置
SET @startPoint = ifnull((_PageIndex-1)*_PageSize,0);
SET @sql= ' SELECT A.*
FROM mysqltestuser A
INNER JOIN _TempTable_KeyID B
ON A.userid =B.userid ';
SET @sql=CONCAT(@sql, " LIMIT ",@startPoint, " , ",_PageSize);
PREPARE stmt FROM @sql;
EXECUTE stmt ;
DEALLOCATE PREPARE stmt;
END;
END IF;
DROP TABLE _TempTable_KeyID;
END;
下面是mysqltestuser表的ddl:
CREATE TABLE `mysqltestuser` (
`userid` int(11) NOT NULL auto_increment,
`name` varchar(50) default NULL,
`chinesename` varchar(50) default NULL,
`registerdatetime` datetime default NULL,
`jf` decimal(20,2) default NULL,
`description` longtext,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
插入些数据:
INSERT INTO `mysqltestuser` (`userid`, `name`, `chinesename`, `registerdatetime`, `jf`, `description`) VALUES
(1, 'xuu1 ', '张飞1 ', '2007-03-29 12:54:41 ',1.5, 'description1 '),
(2, 'xuu2 ', '张飞2 ', '2007-03-29 12:54:41 ',2.5, 'description2 '),
(3, 'xuu3 ', '张飞3 ', '2007-03-29 12:54:41 ',3.5, 'description3 '),
(4, 'xuu4 ', '张飞4 ', '2007-03-29 12:54:41 ',4.5, 'description4 '),
(5, 'xuu5 ', '张飞5 ', '2007-03-29 12:54:41 ',5.5, 'description5 '),
(6, 'xuu6 ', '张飞6 ', '2007-03-29 12:54:41 ',6.5, 'description6 '),
(7, 'xuu7 ', '张飞7 ', '2007-03-29 12:54:41 ',7.5, 'description7 '),
(8, 'xuu8 ', '张飞8 ', '2007-03-29 12:54:41 ',8.5, 'description8 '),
(9, 'xuu9 ', '张飞9 ', '2007-03-29 12:54:41 ',9.5, 'description9 '),
(10, 'xuu10 ', '张飞10 ', '2007-03-29 12:54:41 ',10.5, 'description10 '),
(11, 'xuu11 ', '张飞11 ', '2007-03-29 12:54:41 ',11.5, 'description11 '),
(12, 'xuu12 ', '张飞12 ', '2007-03-29 12:54:41 ',12.5, 'description12 '),
(13, 'xuu13 ', '张飞13 ', '2007-03-29 12:54:41 ',13.5, 'description13 '),
(14, 'xuu14 ', '张飞14 ', '2007-03-29 12:54:41 ',14.5, 'description14 '),
(15, 'xuu15 ', '张飞15 ', '2007-03-29 12:54:41 ',15.5, 'description15 '),
(16, 'xuu16 ', '张飞16 ', '2007-03-29 12:54:41 ',16.5, 'description16 '),
(17, 'xuu17 ', '张飞17 ', '2007-03-29 12:54:41 ',17.5, 'description17 '),
(18, 'xuu18 ', '张飞18 ', '2007-03-29 12:54:41 ',18.5, 'description18 '),
(19, 'xuu19 ', '张飞19 ', '2007-03-29 12:54:41 ',19.5, 'description19 '),
(20, 'xuu20 ', '张飞20 ', '2007-03-29 12:54:41 ',20.5, 'description20 '),
(21, 'xuu21 ', '张飞21 ', '2007-03-29 12:54:41 ',21.5, 'description21 '),
(22, 'xuu22 ', '张飞22 ', '2007-03-29 12:54:41 ',22.5, 'description22 '),
(23, 'xuu23 ', '张飞23 ', '2007-03-29 12:54:41 ',23.5, 'description23 '),
(24, 'xuu24 ', '张飞24 ', '2007-03-29 12:54:41 ',24.5, 'description24 '),
(25, 'xuu25 ', '张飞25 ', '2007-03-29 12:54:41 ',25.5, 'description25 '),
(26, 'xuu26 ', '张飞26 ', '2007-03-29 12:54:41 ',26.5, 'description26 '),
(27, 'xuu27 ', '张飞27 ', '2007-03-29 12:54:41 ',27.5, 'description27 '),
(28, 'xuu28 ', '张飞28 ', '2007-03-29 12:54:41 ',28.5, 'description28 '),
(29, 'xuu29 ', '张飞29 ', '2007-03-29 12:54:41 ',29.5, 'description29 '),
(30, 'xuu30 ', '张飞30 ', '2007-03-29 12:54:41 ',30.5, 'description30 '),
(31, 'xuu31 ', '张飞31 ', '2007-03-29 12:54:41 ',31.5, 'description31 '),
(32, 'xuu32 ', '张飞32 ', '2007-03-29 12:54:41 ',32.5, 'description32 '),
(33, 'xuu33 ', '张飞33 ', '2007-03-29 12:54:41 ',33.5, 'description33 '),
(34, 'xuu34 ', '张飞34 ', '2007-03-29 12:54:41 ',34.5, 'description34 '),
(35, 'xuu35 ', '张飞35 ', '2007-03-29 12:54:41 ',35.5, 'description35 '),
(36, 'xuu36 ', '张飞36 ', '2007-03-29 12:54:41 ',36.5, 'description36 '),
(37, 'xuu37 ', '张飞37 ', '2007-03-29 12:54:41 ',37.5, 'description37 '),
(38, 'xuu38 ', '张飞38 ', '2007-03-29 12:54:41 ',38.5, 'description38 '),
(39, 'xuu39 ', '张飞39 ', '2007-03-29 12:54:41 ',39.5, 'description39 '),
(40, 'xuu40 ', '张飞40 ', '2007-03-29 12:54:41 ',40.5, 'description40 '),
(41, 'xuu41 ', '张飞41 ', '2007-03-29 12:54:41 ',41.5, 'description41 '),
(42, 'xuu42 ', '张飞42 ', '2007-03-29 12:54:41 ',42.5, 'description42 '),
(43, 'xuu43 ', '张飞43 ', '2007-03-29 12:54:41 ',43.5, 'description43 '),
(44, 'xuu44 ', '张飞44 ', '2007-03-29 12:54:41 ',44.5, 'description44 '),
(45, 'xuu45 ', '张飞45 ', '2007-03-29 12:54:41 ',45.5, 'description45 '),
(46, 'xuu46 ', '张飞46 ', '2007-03-29 12:54:41 ',46.5, 'description46 '),
(47, 'xuu47 ', '张飞47 ', '2007-03-29 12:54:41 ',47.5, 'description47 '),
(48, 'xuu48 ', '张飞48 ', '2007-03-29 12:54:41 ',48.5, 'description48 '),
(49, 'xuu49 ', '张飞49 ', '2007-03-29 12:54:41 ',49.5, 'description49 '),
(50, 'xuu50 ', '张飞50 ', '2007-03-29 12:54:41 ',50.5, 'description50 ');
存储过程调用测试:
-- 方法原型 `mysqltestuser_SELECT_PageAble`(条件,排列顺序,每页记录数,第几页,是否统计数据)
-- call `mysqltestuser_SELECT_PageAble`(_WhereClause ,_OrderBy ,_PageSize ,_PageIndex , _DoCount)
-- 统计数据
call `mysqltestuser_SELECT_PageAble`(null, null, null, null, 1)
-- 输出数据,没条件限制,10条记录/页,第一页
call `mysqltestuser_SELECT_PageAble`(null, null, 10, 1,0)
-- 输出数据,条件限制,排列, 10条记录/页,第一页
call `mysqltestuser_SELECT_PageAble`( 'chinesename like ' '%飞3% ' ' ', 'userid asc ', 10, 1, 0)
如果你对改存储过程有什么改进和优化的地方,欢迎指教!
1.索引作用
在索引列上,除了上面提到的有序查找之外,数据库利用各种各样的快速定位技术,能够大大提高查询效率。特别是当数据量非常大,查询涉及多个表时,使用索引往往能使查询速度加快成千上万倍。
例如,有3个未索引的表t1、t2、t3,分别只包含列c1、c2、c3,每个表分别含有1000行数据组成,指为1~1000的数值,查找对应值相等行的查询如下所示。
SELECT c1,c2,c3 FROM t1,t2,t3 WHERE c1=c2 AND c1=c3
此查询结果应该为1000行,每行包含3个相等的值。在无索引的情况下处理此查询,必须寻找3个表所有的组合,以便得出与WHERE子句相配的那些行。而可能的组合数目为1000×1000×1000(十亿),显然查询将会非常慢。
如果对每个表进行索引,就能极大地加速查询进程。利用索引的查询处理如下。
(1)从表t1中选择第一行,查看此行所包含的数据。
(2)使用表t2上的索引,直接定位t2中与t1的值匹配的行。类似,利用表t3上的索引,直接定位t3中与来自t1的值匹配的行。
(3)扫描表t1的下一行并重复前面的过程,直到遍历t1中所有的行。
在此情形下,仍然对表t1执行了一个完全扫描,但能够在表t2和t3上进行索引查找直接取出这些表中的行,比未用索引时要快一百万倍。
利用索引,MySQL加速了WHERE子句满足条件行的搜索,而在多表连接查询时,在执行连接时加快了与其他表中的行匹配的速度。
2. 创建索引
在执行CREATE TABLE语句时可以创建索引,也可以单独用CREATE INDEX或ALTER TABLE来为表增加索引。
1.ALTER TABLE
ALTER TABLE用来创建普通索引、UNIQUE索引或PRIMARY KEY索引。
ALTER TABLE table_name ADD INDEX index_name (column_list)
ALTER TABLE table_name ADD UNIQUE (column_list)
ALTER TABLE table_name ADD PRIMARY KEY (column_list)
其中table_name是要增加索引的表名,column_list指出对哪些列进行索引,多列时各列之间用逗号分隔。索引名index_name可选,缺省时,MySQL将根据第一个索引列赋一个名称。另外,ALTER TABLE允许在单个语句中更改多个表,因此可以在同时创建多个索引。
2.CREATE INDEX
CREATE INDEX可对表增加普通索引或UNIQUE索引。
CREATE INDEX index_name ON table_name (column_list)
CREATE UNIQUE INDEX index_name ON table_name (column_list)
table_name、index_name和column_list具有与ALTER TABLE语句中相同的含义,索引名不可选。另外,不能用CREATE INDEX语句创建PRIMARY KEY索引。
3.索引类型
在创建索引时,可以规定索引能否包含重复值。如果不包含,则索引应该创建为PRIMARY KEY或UNIQUE索引。对于单列惟一性索引,这保证单列不包含重复的值。对于多列惟一性索引,保证多个值的组合不重复。
PRIMARY KEY索引和UNIQUE索引非常类似。事实上,PRIMARY KEY索引仅是一个具有名称PRIMARY的UNIQUE索引。这表示一个表只能包含一个PRIMARY KEY,因为一个表中不可能具有两个同名的索引。
下面的SQL语句对students表在sid上添加PRIMARY KEY索引。
ALTER TABLE students ADD PRIMARY KEY (sid)
4. 删除索引
可利用ALTER TABLE或DROP INDEX语句来删除索引。类似于CREATE INDEX语句,DROP INDEX可以在ALTER TABLE内部作为一条语句处理,语法如下。
DROP INDEX index_name ON talbe_name
ALTER TABLE table_name DROP INDEX index_name
ALTER TABLE table_name DROP PRIMARY KEY
其中,前两条语句是等价的,删除掉table_name中的索引index_name。
第3条语句只在删除PRIMARY KEY索引时使用,因为一个表只可能有一个PRIMARY KEY索引,因此不需要指定索引名。如果没有创建PRIMARY KEY索引,但表具有一个或多个UNIQUE索引,则MySQL将删除第一个UNIQUE索引。
如果从表中删除了某列,则索引会受到影响。对于多列组合的索引,如果删除其中的某列,则该列也会从索引中删除。如果删除组成索引的所有列,则整个索引将被删除。
5.查看索引
mysql> show index from tblname;
mysql> show keys from tblname;
· Table
表的名称。
· Non_unique
如果索引不能包括重复词,则为0。如果可以,则为1。
· Key_name
索引的名称。
· Seq_in_index
索引中的列序列号,从1开始。
· Column_name
列名称。
· Collation
列以什么方式存储在索引中。在MySQL中,有值‘A’(升序)或NULL(无分类)。
· Cardinality
索引中唯一值的数目的估计值。通过运行ANALYZE TABLE或myisamchk -a可以更新。基数根据被存储为整数的统计数据来计数,所以即使对于小型表,该值也没有必要是精确的。基数越大,当进行联合时,MySQL使用该索引的机会就越大。
· Sub_part
如果列只是被部分地编入索引,则为被编入索引的字符的数目。如果整列被编入索引,则为NULL。
· Packed
指示关键字如何被压缩。如果没有被压缩,则为NULL。
· Null
如果列含有NULL,则含有YES。如果没有,则该列含有NO。
· Index_type
用过的索引方法(BTREE, FULLTEXT, HASH, RTREE)。
· Comment
更多评注。
909024917
浙公网安备 33010602011771号