ASP.NET中操作Word文件?
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;
using System.Data.OleDb;
private void btnOK_Click(object sender, System.EventArgs e)
{
try
{
object Nothing=System.Reflection.Missing.Value;//调用默认参数
//取得Word文件保存路径
object filename=@tbPath.Text;
//object visible=false;
//创建一个名为WordApp的组件对象
Word.Application WordApp=new Word.ApplicationClass();
//创建一个名为WordDoc的文档对象
object missing = System.Reflection.Missing.Value;
Word.Document WordDoc=WordApp.Documents.Add(ref missing,ref missing,ref missing,ref missing);
//增加一表格
Word.Table table=WordDoc.Tables.Add(WordApp.Selection.Range,1,1,ref Nothing,ref Nothing);
//在表格第一单元格中添加自定义的文字内容
table.Cell(1,1).Range.Text=tbBody.Text;
//在文档空白地方添加文字内容
WordDoc.Paragraphs.Last.Range.Text="欢迎参加.NET学习!";
//将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);
//返回结果
lbResult.Text="文档路径:<a href='"+tbPath.Text+"'>"+tbPath.Text+"</a>(点击链接查看)<br>生成结果:成功!";
}
catch(Exception Ex)
{
string str = Ex.Message;
Response.Write(str);
}
}
ASP.NET中操作EXCEL文件?
private Excel.Application objExcel = null;
private Excel.Workbooks objBooks = null;
private Excel._Workbook objBook = null;
private Excel.Sheets objSheets = null;
private Excel._Worksheet objSheet = null;
private Excel.Range objRange = null;
private Excel.Font objFont = null;
private void btnAdo_Click(object sender, System.EventArgs e)
{
// Establish a connection to the data source.
OleDbConnection objConn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strSampleFolder +
"new.xls;Extended Properties=Excel 8.0;");
objConn.Open();
// Add two records to the table named 'MyTable'.
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = objConn;
objCmd.CommandText = "CREATE TABLE MyTable2 (FirstName char(255),LastName char(255))";
objCmd.ExecuteNonQuery();
// objCmd.CommandText = "Insert into MyTable (FirstName, LastName)" +
// " values ('shao', 'zhidong')";
// objCmd.ExecuteNonQuery();
// objCmd.CommandText = "Insert into MyTable (FirstName, LastName)" +
// " values ('张', '三')";
// objCmd.ExecuteNonQuery();
// Close the connection.
objConn.Close();
}
private void btnAuto_Click(object sender, System.EventArgs e)
{
// Start a new workbook in Excel.
objExcel = new Excel.Application();
objBooks = (Excel.Workbooks)objExcel.Workbooks;
objBook = (Excel._Workbook)(objBooks.Add(objOpt));
// Add data to cells of the first worksheet in the new workbook.
objSheets = (Excel.Sheets)objBook.Worksheets;
objSheet = (Excel._Worksheet)(objSheets.get_Item(1));
objRange = objSheet.get_Range("A1", objOpt);
objRange.set_Value(objOpt,"Last Name");
objRange = objSheet.get_Range("B1", objOpt);
objRange.set_Value(objOpt,"First Name");
objRange = objSheet.get_Range("A2", objOpt);
objRange.set_Value(objOpt,"shao");
objRange = objSheet.get_Range("B2", objOpt);
objRange.set_Value(objOpt,"zhidong");
// Apply bold to cells A1:B1.
objRange = objSheet.get_Range("A1", "B1");
objFont = objRange.Font;
objFont.Bold=true;
// Save the workbook and quit Excel.
objBook.SaveAs(strSampleFolder + "Book1.xls", objOpt, objOpt,
objOpt, objOpt, objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
objOpt, objOpt, objOpt, objOpt, objOpt);
objBook.Close(false, objOpt, objOpt);
objExcel.Quit();
}
用户控件适用于:
–页面上的重复元素,比如标题、菜
单、登录控件等。
–将重复元素封装到用户控件中,减
少每页的代码量
主页面添加控件:
<%@ Register TagPrefix="uc1" TagName="MikeCatCtr" Src="MikeCatCtr.ascx" %>
private void Page_Load(object sender, System.EventArgs e)
{
Page.Controls.Add(new HtmlGenericControl("hr"));
Control c1 = LoadControl("MikeCatCtr.ascx");
((MikeCatCtr)c1).Category = "business";
Page.Controls.Add(c1);
Page.Controls.Add(new HtmlGenericControl("hr"));
Control c2 = LoadControl("MikeCatCtr.ascx");
((MikeCatCtr)c2).Category = "trad_cook";
Page.Controls.Add(c2);
Page.Controls.Add(new HtmlGenericControl("hr"));
Control c3 = LoadControl("MikeCatCtr.ascx");
((MikeCatCtr)c3).Category = "mod_cook";
Page.Controls.Add(c3);
}
控件页面:
<%@ Control Language="c#" AutoEventWireup="false" Codebehind="MikeCatCtr.ascx.cs" Inherits="ASPNETUseCom.UseControl.MikeCatCtr" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<span style="FONT: 12pt verdana">Category:
<%=Category%>
</span>
<ASP:DataList id="MyDataList" BorderWidth="0" RepeatColumns="2" runat="server">
<ItemTemplate>
<table cellpadding="10" style="font: 10pt verdana">
<tr>
<td valign="top">
<b>Title: </b>
<%# DataBinder.Eval(Container.DataItem, "title") %>
<br>
<b>Category: </b>
<%# DataBinder.Eval(Container.DataItem, "type") %>
<br>
<b>Publisher ID: </b>
<%# DataBinder.Eval(Container.DataItem, "pub_id") %>
<br>
<b>Price: </b>
<%# DataBinder.Eval(Container.DataItem, "price", "$ {0}") %>
</td>
</tr>
</table>
</ItemTemplate>
</ASP:DataList>
namespace ASPNETUseCom.UseControl
{
using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
/// <summary>
/// MikeCatCtr 的摘要说明。
/// </summary>
public abstract class MikeCatCtr : System.Web.UI.UserControl
{
protected System.Web.UI.WebControls.DataList MyDataList;
private String _category = "";
public String Category
{
get
{
return _category;
}
set
{
_category = value;
SqlConnection myConnection = new SqlConnection("server=(local);database=pubs;uid=sa;pwd=111");
SqlDataAdapter myCommand = new SqlDataAdapter("select * from Titles where type='" + _category + "'", myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "Titles");
MyDataList.DataSource = ds.Tables["Titles"].DefaultView;
MyDataList.DataBind();
}
}
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// 设计器支持所需的方法 - 不要使用
/// 代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
?? VS.NET中用户控件的创建
?? 新建ASP.NET Web应用程序
?? 在“项目”菜单中选择“添加Web用户控件”
?? 创建界面元素
设计方式:
– 把*.ascx文件拖动到*.aspx页面上,即可添加用户
控件
? 编码方式
– myTBPlus =
(TextBoxPlus)LoadControl("TextBoxPlus.ascx");
– PlaceHolder1.Controls.Add(myTBPlus);
用户控件小结
? 用户控件使开发人员能够使用编写Web 窗体
页的相同编程技巧轻松地定义自定义控件。
? 作为约定,用.ascx 文件扩展名指示这样的
控件。
? 用户控件通过Register 指令包括在另一Web
窗体页中,该指令指定TagPrefix、
TagName 和Src location。
? 注册了用户控件后,可以像普通的服务器控
件那样将用户控件标记放置在Web 窗体页中
(包括runat=“server” 属性)。
在包含Web 窗体页中将用户控件的公共字
段、属性和方法提升为该控件的公共属性
(标记属性)和方法。
? 用户控件参与每个请求的整个执行生存
期,并且可以处理自己的事件,封装来自
包含Web 窗体页的一些页逻辑。
? 可以使用System.Web.UI.Page 类的
LoadControl 方法以编程方式创建用户控件。
用户控件的类型由ASP.NET 运行库决定,
遵循约定文件名_扩展名。
实现一个ASP.NET Back控件
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
namespace WebControlsEx
{
/// <summary>
/// Sends user to the URL of the client's previous request that linked to the current URL.
/// </summary>
[ToolboxData("<{0}:BackLink runat=server></{0}:BackLink>")]
[ToolboxBitmap(typeof(BackLink),"BackLink.bmp")]
public class BackLink : LinkButton
{
public BackLink()
{
Text = "Back";
ToolTip = "Click to go to the previous page";
}
protected override void OnClick(EventArgs e)
{
Uri backURL = (Uri)Page.Session["Referring URL"];
Page.Session["Referring URL"] = null;
if(backURL != null)
{
Page.Response.Redirect(backURL.AbsoluteUri);
}
}
protected override void OnLoad(EventArgs e)
{
Uri backURL = Page.Request.UrlReferrer;
if(backURL == null) //No referrer information
{
Enabled = false;
return;
}
if(backURL.AbsolutePath != Page.Request.Url.AbsolutePath)
{
Page.Session["Referring URL"] = backURL;
Enabled = true;
return;
}
else
{
object obj = Page.Session["Referring URL"];
if(obj != null)
{
Enabled = true;
}
}
base.OnLoad(e);
}
}
}