ASP用模板生成Excel、Word
c#Aspose.Cells通过Excel模板生产excel数据再打印

c#Aspose.Cells通过Excel模板⽣产excel数据再打印多的不说,我们先来利⽤Northwind做两个⼩demo。
先说说Aspose.Cells的模板语法:1. &=DataSource.Field,&=[DataSource].[Field]是对DataTable和⼏何类型的引⽤,将会从当前⾏开始竖直向下⽣成多⾏数据。
2. &=$data:是对变量或数组的引⽤。
数组存在skip,horizontal等属性,具体参见3. &=&=动态公式计算;{r}当前⾏,{c}当前列,{-n},{n}当前⾏或列的偏移量前n或后n。
4. &==是动态计算,如excel,if等语句。
(if(logic_test,true_value,false_value))还有其他更为复杂的汇总计算的表达式,这⾥也不在这节多讲,有兴趣的朋友,可以去官⽹看看。
我们先来个简单的例⼦,光说,总是不⾏的,还是要代码实践才能说明⼀切:代码如下:App_Code.SqlDbHelper help = new App_Code.SqlDbHelper();var s = Aspose.Cells.CellsHelper.GetVersion();var sql = "select WL_TZ,WL_CL,RPCJH_SL,WL_MC,RPCJH_JHKGRQ,RPCJH_JHID,RPCJH_JHID asRPCJH_JHID1,RPCJH_GXID,U_RPCJH_KH,(select rtrim((cast(GYLX_GXID as char(2)))+' '+ltrim(GYLX_GXMC)) from GYLX whereGYLX_GYLXID=wo.WO_GYLXID and GYLX_GXID=RPCJH_GXID) as gxmc from RPCJH left join wl on RPCJH_WLID=WL_WLID left join wo on wo.WO_WOID=RPCJH_WOID where RPCJH_JHID='JHA1909152' and RPCJH_BZGXID!='888' ";var dt = help.ExecuteDataTable(sql);dt.TableName = "Customers";Workbook workBook = new Workbook(@"E:\KaBoProject\GTDB\GTDB\bin\Debug\机加作业计划卡.xls");WorkbookDesigner designer = new WorkbookDesigner(workBook);//数据源designer.SetDataSource(dt);//报表单位designer.SetDataSource("RPCJH_JHID", dt.Rows[0]["RPCJH_JHID"].ToString().Trim());designer.SetDataSource("U_RPCJH_KH", dt.Rows[0]["U_RPCJH_KH"].ToString().Trim());designer.SetDataSource("RPCJH_JHID1", "计划编号:" + dt.Rows[0]["RPCJH_JHID1"].ToString().Trim() + " 领卡⼈:");designer.SetDataSource("RPCJH_JHKGRQ", "派⼯⽇期:" +Convert.ToDateTime(dt.Rows[0]["RPCJH_JHKGRQ"].ToString().Trim()).ToShortDateString());designer.SetDataSource("WL_MC", "名称:" + dt.Rows[0]["WL_MC"].ToString().Trim());designer.SetDataSource("WL_TZ", dt.Rows[0]["WL_TZ"].ToString().Trim());designer.SetDataSource("WL_CL", dt.Rows[0]["WL_CL"].ToString().Trim());designer.SetDataSource("RPCJH_SL", dt.Rows[0]["RPCJH_SL"].ToString().Trim());designer.Process();workBook.Save(@"E:\KaBoProject\GTDB\GTDB\bin\Debug\2.xls", SaveFormat.Xlsx);designer = null;⽣成的excel如下打印代码如下:Workbook workbook = new Workbook(@"E:\KaBoProject\GTDB\GTDB\bin\Debug\2.xls");//Get the worksheet to be printedWorksheet worksheet = workbook.Worksheets[0];//获取该Excel⽂档的第⼀个⼯作表//PageSetup pageSetup = worksheet.PageSetup;//pageSetup.Orientation = ndscape;//pageSetup.LeftMargin = 0;//pageSetup.RightMargin = 0.1;//pageSetup.BottomMargin = 0.3;//pageSetup.PrintArea = "A2:J29";//Apply different Image / Print options.Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions(); //Set the Printing page property//options.PrintingPage = PrintingPageType.IgnoreStyle;//Render the worksheetSheetRender sr = new SheetRender(worksheet, options);System.Drawing.Printing.PrinterSettings printSettings = new System.Drawing.Printing.PrinterSettings();string strPrinterName = printSettings.PrinterName;//send to printer//System.Drawing.Image map = sr.ToImage(0);sr.ToPrinter(strPrinterName);。
asp.net里导出excel表方法汇总

HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
用法:ToExcel(datagrid1);
4、这个用dataview ,代码好长
//
//设置报表表格为最适应宽度
//
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Columns.AutoFit();
}
//
//取得表格中的数据
//
foreach(DataRowView row in dv)
{
rowIndex ++;
colIndex = 1;
foreach(DataColumn col in dv.Table.Columns)
{
colIndex ++;
//
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//设置为浅黄色,共计有56种
HttpContext.Current.Response.Charset ="UTF-8";
ASP对Excel的所有操作

A: 同一用户生成的Excel文件用同一个文件名,文件名可用用户ID号或SessionID号等可确信不重复字符串组成。这样新文件生成时自动覆盖上一文件。
B: 在Global.asa文件中设置Session_onEnd事件激发时,删除这个用户的Excel暂存文件。
C: 在Global.asa文件中设置Application_onStart事件激发时,删除暂存目录下的所有文件。
6、 绑定Chart图
objExcelApp.ActiveChart.Location 1
7、 显示数据表
objExcelApp.ActiveChart.HasDataTable = True
8、 显示图例
objExcelApp.ActiveChart.DataTable.ShowLegendKey = True
目录
一、 环境配置
二、 ASP对Excel的基本操作
三、 ASP操作Excel生成数据表
四、 ASP操作E件浏览、下载、删除方案
六、 附录
正文
一、 环境配置
服务器端的环境配置从参考资料上看,微软系列的配置应该都行,即:
1.Win9x+PWS+Office
2、 新建Excel文件
objExcelApp.WorkBooks.add
set objExcelBook = objExcelApp.ActiveWorkBook
set objExcelSheets = objExcelBook.Worksheets
set objExcelSheet = objExcelBook.Sheets(1)
将asp图片导出Excel的方法

将asp图片导出Excel的方法小编在网上找了很多要将asp图片导出Excel的方法,当时网上很多都是着实虚无,目前所知的方法有4种。
1.网上包括csdn大部分流行的方法,强制输出html格式为xls格式。
优点效率高,速度快。
缺点也很明显,毕竟不是真正的Excel格式,只是利用了office2000以后的版本可以直接打开html文件的特性强制生成的。
无法改变单元格格式等。
尤其是office2007,打开会提示您尝试打开的*xls"的格式与文件扩展名指定的格式不一致。
并且按保存时,会发现默认格式是txt。
这种方法不建议使用。
2.JavaScript格式,粗略的看了下。
有个致命的问题,要设置ie 安全属性。
一般用户会为了一个功能去繁琐的更高ie设置?而且也不是真正的csv格式,xls格式而已。
不考虑。
3.第三方控件,使用过MyXls这个控件,生成的真正的xls文件。
效率高,使用简单,不用考虑资源释放的问题。
可惜未发现导出图片的方法。
不过一般导出Excel的话,强烈推荐!4.使用微软的官方COM组件。
优点:功能强大。
缺点:效率低,需要手动关闭进程,释放资源,而且服务器端还需安装office。
暂时只发现这个可以导出图象到Excel。
方法如下:虽然服务器必须安装office,但并不需要安装完整版本的office,本人发现精简版也可以。
只不过设置麻烦一些而已。
先安装O2003PIA补丁。
下载地址百度。
网上一堆。
如果你安装完整版的office,可以跳过这部。
然后导入COM组件确定即可。
然后添加引用,如果安装的是完整版的,直接在引用的tab框中添加即可。
如果您是精简版的,下载个Microsoft.Office.Interop.Excel.dll。
然后放到网站根目录代码如下using System;using System.Data;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;//导入Com组件using Microsoft.Office.Core;//添加引用using ex=Microsoft.Office.Interop.Excel;using System.Reflection;public partial class _Default : System.Web.UI.Page {////// 导出图象到Excel/// 创建人:吴凯平/// 创建时间:2010年1月3日 12:46:38/////////protected void Page_Load(object sender, EventArgs e) {}////// 导出到Excel/////////protected void btnExcel_Click(object sender, EventArgs e){//声明一个默认值object missing = Missing.Value;//声明一个Excel应用程序对象ex.Application excelObj = new ex.ApplicationClass();//禁用Excel提示(否则第二次生成会提示是否覆盖等..)excelObj.DisplayAlerts = false;//不显示excel??excelObj.Visible = false;//创建workbooksex.Workbooks wbooks = excelObj.Workbooks;//使用Excel模板创建一个工作簿(模板必须先创建好放在网站可访问目录下)ex.Workbook wbook = wbooks.Open(Server.MapPath("模板路径"), missing, missing,missing, missing, missing, missing, missing, missing, missing, missing, missing, missing,missing, missing);//新建一个excel工作表集合ex.Worksheets sheets = (ex.Worksheets)wbook.Worksheets;//新建一个工作表ex._Worksheet sheet = (ex._Worksheet)sheets.get_Item(1);//声明一个pictures对象,用来存放sheet的图片ex.Pictures pics = (ex.Pictures)sheet.Pictures(missing);//设置要插入的图片路径pics.Insert(Server.MapPath("图片路径"),MsoTriState.msoFalse, MsoTriState.msoCTrue);//插入图片}}////// 输出Excel/////////protected void ImageButton1_Click(object sender, ImageClickEventArgs e){if (chltStat.Visible == false){ClientScript.RegisterStartupScript(GetType(), "", "alert('没有数据请生成数据再导入!');", true);return;}object missing = Missing.Value;//定义一个Excel应用程序ex.ApplicationClass excelObj = new ex.ApplicationClass();excelObj.DisplayAlerts = false;excelObj.Visible = false;ex.Workbooks wbooks = excelObj.Workbooks;ex.Workbook wbook = wbooks.Open(Server.MapPath("../动态经营统计数据.xls"), missing, missing, missing, missing, missing, missing,missing, missing, missing, missing, missing, missing, missing, missing);ex.Sheets sheets = (ex.Sheets)wbook.Worksheets;ex._Worksheet sheet = (ex._Worksheet)sheets.get_Item(1);ex.Range exRange = (ex.Range)sheet.get_Range("B2", missing);exRange.Select();//声明一个pictures对象,用来存放柱状图ex.Pictures pics = (ex.Pictures)sheet.Pictures(missing);//插入图片pics.Insert(Server.MapPath("Chartlet_chltStat_区企业年度信息统计表_Bar.Jpg"), missing);sheet.Shapes.AddPicture(Server.MapPath("Chartlet_chltStat 2_区企业年度信息统计表_Line.Jpg"),Microsoft.Office.Core.MsoTriState.msoFalse,Microsoft.Office.Core.MsoTriState.msoCTrue,50, 400, 570, 368);//504 326wbook.SaveAs(Server.MapPath("../xls/动态经营统计数据.xls"), missing, missing, missing, missing, missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoCh ange, missing, missing, missing, missing,missing);wbook.Close(false, missing, missing);excelObj.Quit();ClientScript.RegisterStartupScript(GetType(), "", "window.location.href='../xls/动态经营统计数据.xls';", true);//必须关闭释放所引用的COM对象,关闭Excel进程,否则会占用服务器资源ReleaseObj(sheets);ReleaseObj(wbook);ReleaseObj(wbooks);ReleaseObj(excelObj);System.GC.Collect();System.GC.WaitForPendingFinalizers();//BindGv();string filePath = Server.MapPath("../xls/动态经营统计数据.xls");Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");Response.AppendHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("动态经营统计数据", System.Text.Encoding.UTF8) + ".xls");Response.ContentType = "Application/excel";Response.WriteFile(filePath);Response.End();}。
在ASP中怎么把页面中的数据导出到EXCEL

使用asp怎样将数据导出到excel文件 Web注意:两个函数中的“data“是网页中要导出的table的 id<input type="hidden" name="out_word" onclick="vbscript:buildDoc" value="导出到word" class="notPrint"><input type="hidden" name="out_excel" onclick="AutomateExcel();" value="导出到excel" class="notPrint">导出到Excel代码<SCRIPT LANGUAGE="JavaScript"><!--function AutomateExcel(){// Start Excel and get Application object.var oXL = new ActiveXObject("Excel.Application");// Get a new workbook.var oWB = oXL.Workbooks.Add();var oSheet = oWB.ActiveSheet;var table = document.all.data;var hang = table.rows.length;var lie = table.rows(0).cells.length;// Add table headers going cell by cell.for (i=0;i<hang;i++){for (j=0;j<lie;j++){oSheet.Cells(i+1,j+1).Value = table.rows(i).cells(j).innerText;}}oXL.Visible = true;erControl = true;}//--></SCRIPT>导出到Word代码<script language="vbscript">Sub buildDocset table = document.all.datarow = table.rows.lengthcolumn = table.rows(1).cells.lengthSet objWordDoc = CreateObject("Word.Document")'objWordDoc.Application.Documents.Add theTemplate, FalseobjWordDoc.Application.Visible=TrueDim theArray(20,10000)for i=0 to row-1for j=0 to column-1theArray(j+1,i+1) = table.rows(i).cells(j).innerTEXTnextnextobjWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertBefore("综合查询结果集") //显示表格标题objWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertBefore("") Set rngPara = objWordDoc.Application.ActiveDocument.Paragraphs(1).Range With rngPara.Bold = True //将标题设为粗体.ParagraphFormat.Alignment = 1 //将标题居中 = "隶书" //设定标题字体.Font.Size = 18 //设定标题字体大小End WithSet rngCurrent = objWordDoc.Application.ActiveDocument.Paragraphs(3).RangeSet tabCurrent = ObjWordDoc.Application.ActiveDocument.Tables.Add(rngCurrent,row,column)for i = 1 to columnobjWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.InsertAfter theArray(i,1)objWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.Paragraph Format.alignment=1nextFor i =1 to columnFor j = 2 to rowobjWordDoc.Application.ActiveDocument.Tables(1).Rows(j).Cells(i).Range.InsertAfter theArray(i,j)objWordDoc.Application.ActiveDocument.Tables(1).Rows(j).Cells(i).Range.Paragraph Format.alignment=1NextNextEnd Sub</SCRIPT>在ASP中怎么把页面中的数据导出到EXCEL直接读SQL库,我想也可以用来解决你的问题,(同理:页面上显示的内容当然也是读库的,除非你是静态的那算了)<!--#include file="../opendb.asp"--><!--写链接的事不用我弄了吧?--><title>生成报表</title><%dim conn,strconnset conn=server.CreateObject("adodb.connection")conn.Open ConnStrdim rs,sql,filename,fs,myfile,xSet fs = server.CreateObject("scripting.filesystemobject")filepath=Request.ServerVariables("APPL_PHYSICAL_PATH")filename = filepath&"temp_xls\"&year(now)&month(now)&day(now)&".xls"if fs.FileExists(filename) thenfs.DeleteFile(filename)end ifset myfile = fs.CreateTextFile(filename,true)Set rs = Server.CreateObject("ADODB.Recordset")sql = "select * from jdxx"rs.Open sql,conn,1,1if rs.EOF and rs.BOF thenelsedim strLine,responsestrstrLine=""For each x in rs.fieldsstrLine = strLine & & chr(9)Nextmyfile.writeline strLineDo while Not rs.EOFstrLine=""for each x in rs.FieldsstrLine = strLine & x.value & chr(9)nextmyfile.writeline strLiners.MoveNextloopend ifrs.Closeset rs = nothingremotefile="http://xxx.xxx.x.xxx/temp_xls/"&year(now)&month(now)&day(now)&".xls" response.write "<font size=2 color=blue>报表巳生成,<a href="&remotefile&">请点击这里下载该报表!</a></font>"%>在ASP中怎么把页面中的数据导出到EXCEL<%@ LANGUAGE="VBSCRIPT" CODEPAGE="950"%><%'關鍵所在Response.ContentType = "application/vnd.ms-excel"Set conn=Server.CreateObject("ADODB.Connection")Set rs=Server.CreateObject("ADODB.Recordset")strconn = "Provider = SQLOLEDB; Data Source = 192.168.0.2; Uid=gt_bbs;Pwd=gt_bbs;DataBase=gt_bbs"conn.open strconnSQL="Select top 100 id,uid,uer,bm,zw,zb,gxrq,ip,be From Gt_user order by id desc"rs.Open SQL,conn,3,1if rs.eof and rs.bof thenResponse.Write"<div align=center><br>沒有任何記錄</div>"else%><TABLE cellSpacing=0 cellPadding=0 width="100%" border=1><TR><TD width=12% height="25" class=borderon> 代 </TD> <TD width="11%" class=borderon> 名</TD><TD width="11%" class=borderon> 部門</TD><TD width="14%" class=borderon> </TD><TD width="6%" class=borderon> 別</TD><TD width="16%" class=borderon> 登</TD><TD width="16%" class=borderon> 登 IP</TD> </TR></TABLE><TABLE width="100%" border=1 cellPadding=0 cellSpacing=0><%do while (Not RS.Eof) and (I<RS.PageSize)%><TR bgcolor=<%=bg2%>><TD class=all width=12% height=20 > <%=rs(1)%></TD> <TD width="11%" class=all> <%=rs(2)%></TD><TD width="11%" class=all> <%=rs(3)%></TD><TD width="14%" class=all> <%=rs(4)%></TD><TD width="6%" class=all> <%=rs(5)%></TD><TD width="16%" class=all> <%=rs(6)%></TD><TD width="16%" class=all> <%=rs(7)%></TD></TR><%Rs.MoveNextLoopend IFSet Conn = NothingSet Rs = Nothing%></TABLE>。
在ASP.NET中将GridView数据导出到Word、Excel

《 榔帕吉 E ll
…
} c nCls ; o . oe0
鬈__¨ E_ l 蝤豳墨—■■豳———圈啊一 x_l c l e _ , l 一 l
. .
D l 一 一 …~
z鐾 l io 培
~一一 …
} }
i8- 961 秘 2
2 G iV e r iw导 出到 E cl 件 d xe文
【 . n e t n 】. n e t n tig .Co n c o ” Co n ci S r ); i o n
c nO e ; o .pn 0
Ol Db mm a d c mma d = n w e C mma d r e Co n o n e OlDb o n ”
S lc fo S o ee t rm h wme c n ”, o );
Ol DbDaa a r d t e tRe de aaRe de = c m m a Exe a r o nd. -
ap . sx S及 We . n g C bc f 。采 用 了 A cs 数 据库 ,名 为 C s m . oi ces ut s o
md ,记 录在 里 面 的表 S o me中 。 因 此需 要 在 E pr aa s b hw x ot t. — D a
实现 了导 出 GiV e 中的数 据 到 Wod xe 文件 。 r iw d r、E cl
关 键 词 :G iV e r iw控 件 ; 据 导 出 ; S . E d 数 A PN T
Ex r t o W o d, c lf r i po tDa a t r Ex e o m GrdVi w n P. e i AS NET
同 的接 口实 现 的 。 实 现 该 功 能 涉 及 3个 文 件 :E pr aa s x x otaa xot t. p 、E pr t. D a D
asp.net生成Excel并导出下载五种实现方法

⽣成Excel并导出下载五种实现⽅法通过GridView(简评:⽅法⽐较简单,但是只适合⽣成格式简单的Excel,且⽆法保留VBA代码),页⾯⽆刷新aspx.cs部分复制代码代码如下:using System; using System.Collections; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Text; public partial class DataPage_NationDataShow : System.Web.UI.Page { private Data_Link link = new Data_Link(); private string sql; protected void Page_Load(object sender, EventArgs e) { Ajax.Utility.RegisterTypeForAjax(typeof(DataPage_NationDataShow)); } protected void btnExcel_Click(object sender, EventArgs e) { string strExcelName = "MyExcel"; strExcelName = strExcelName.Replace(@"/", ""); Data_Link link = new Data_Link(); string strSQL = this.hidParam.Value; DataSet ds = new DataSet(); ds = link.D_DataSet_Return(strSQL);//获得想要放⼊Excel的数据 gvExcel.Visible = true; gvExcel.DataSource = null; gvExcel.DataMember = ds.Tables[0].TableName; gvExcel.DataSource = ds.Tables[0]; gvExcel.DataBind(); ExportToExcel(this.Page, gvExcel, strExcelName); } protected void gvExcel_RowDataBound(object sender, GridViewRowEventArgs e) { } public override void VerifyRenderingInServerForm(Control control) { } /// <summary> /// ⼯具⽅法,Excel出⼒(解决乱码问题) /// </summary> ///<param name="page">调⽤页⾯</param> /// <param name="excel">Excel数据</param> /// <param name="fileName">⽂件名</param> public void ExportToExcel(System.Web.UI.Page page, GridView excel, string fileName) { try { foreach (GridViewRow row in excel.Rows) { for (int i = 0; i < row.Cells.Count; i++) { excel.HeaderRow.Cells[i].BackColor = System.Drawing.Color.Yellow; } } excel.Font.Size = 10; excel.AlternatingRowStyle.BackColor =System.Drawing.Color.LightCyan; excel.RowStyle.Height = 25; page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); page.Response.Charset = "utf-8"; page.Response.ContentType = "application/vnd.ms-excel"; page.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");excel.Page.EnableViewState = false; excel.Visible = true; excel.HeaderStyle.Reset(); excel.AlternatingRowStyle.Reset(); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); excel.RenderControl(oHtmlTextWriter);page.Response.Write(oStringWriter.ToString()); page.Response.End(); excel.DataSource = null; excel.Visible = false; } catch (Exception e) { } } }aspx部分复制代码代码如下:<head runat="server"> <script type="text/javascript"> //Excel DownLoad function excelExport(){ var hidText = document.getElementById("hidParam"); hidText.value = "some params"; document.getElementById("ExcelOutput").click(); } </script> </head> <body onload="pageInit()"> <form id="form1"runat="server"> <input type="button" value="EXCEL下载" style="width:100px;" onclick="excelExport()" id="excelBut" /><input id="hidParam" type="text" runat="server" style="display:none;"/> <asp:Button runat="server" ID="ExcelOutput"style="display:none" Text= "EXCEL出⼒" Width="0px" onclick="btnExcel_Click" UseSubmitBehavior="false"/><asp:GridView ID="gvExcel" runat="server" Height="95px" OnRowDataBound="gvExcel_RowDataBound" Visible="False"> </asp:GridView> </form> </body>在刚才的aspx.cs代码中复制代码代码如下:foreach (GridViewRow row in excel.Rows) { for (int i = 0; i < row.Cells.Count; i++) { excel.HeaderRow.Cells[i].BackColor = System.Drawing.Color.Yellow; } }这部分是给表头添加样式。
ASP导出Excel数据的四种方法

ASP导出Excel数据的四种方法一、使用OWC什么是OWC?OWC是Office Web Compent的缩写,即Microsoft的Office Web组件,它为在Web中绘制图形提供了灵活的同时也是最基本的机制。
在一个intranet环境中,如果可以假设客户机上存在特定的浏览器和一些功能强大的软件(如IE5和Office 2000),那么就有能力利用Office Web组件提供一个交互式图形开发环境。
这种模式下,客户端工作站将在整个任务中分担很大的比重。
<%Option ExplicitClass ExcelGenPrivate objSpreadsheetPrivate iColOffsetPrivate iRowOffsetSub Class_Initialize()Set objSpreadsheet = Server.CreateObject("OWC.Spreadsheet")iRowOffset = 2iColOffset = 2End SubSub Class_Terminate()Set objSpreadsheet = Nothing "Clean up End SubPublic Property Let ColumnOffset(iColOff) If iColOff > 0 theniColOffset = iColOffElseiColOffset = 2End IfEnd PropertyPublic Property Let RowOffset(iRowOff) If iRowOff > 0 theniRowOffset = iRowOffElseiRowOffset = 2End IfEnd Property Sub GenerateWorksheet(objRS)"Populates the Excel worksheet based on a Recordset"s contents"Start by displaying the titlesIf objRS.EOF then Exit SubDim objField, iCol, iRowiCol = iColOffsetiRow = iRowOffsetFor Each objField in objRS.FieldsobjSpreadsheet.Cells(iRow, iCol).Value = /doc/71b0b63383c4bb4cf7ecd11a.htmlobjSpreadsheet.Columns(iCol).AutoFitColumns"设置Excel表里的字体objSpreadsheet.Cells(iRow, iCol).Font.Bold = True objSpreadsheet.Cells(iRow, iCol).Font.Italic = False objSpreadsheet.Cells(iRow, iCol).Font.Size = 10 objSpreadsheet.Cells(iRow, iCol).Halignment = 2 "居中iCol = iCol + 1Next "objField"Display all of the dataDo While Not objRS.EOFiRow = iRow + 1iCol = iColOffsetFor Each objField in objRS.FieldsIf IsNull(objField.Value) thenobjSpreadsheet.Cells(iRow, iCol).Value = ""ElseobjSpreadsheet.Cells(iRow, iCol).Value = objField.Value objSpreadsheet.Columns(iCol).AutoFitColumns objSpreadsheet.Cells(iRow, iCol).Font.Bold = False objSpreadsheet.Cells(iRow, iCol).Font.Italic = False objSpreadsheet.Cells(iRow, iCol).Font.Size = 10End IfiCol = iCol + 1Next "objFieldobjRS.MoveNextLoopEnd Sub Function SaveWorksheet(strFileName)"Save the worksheet to a specified filenameOn Error Resume NextCall objSpreadsheet.ActiveSheet.Export(strFileName, 0)SaveWorksheet = (Err.Number = 0)End FunctionEnd ClassDim objRSSet objRS = Server.CreateObject("ADODB.Recordset")objRS.Open "SELECT * FROM xxxx", "Provider=SQLOLEDB.1;Persist SecurityInfo=True;User ID=xxxx;Password=xxxx;Initial Catalog=xxxx;Data source=xxxx;"Dim SaveNameSaveName = Request.Cookies("savename")("name")Dim objExcelDim ExcelPathExcelPath = "Excel\" & SaveName & ".xls"Set objExcel = New ExcelGenobjExcel.RowOffset = 1objExcel.ColumnOffset = 1objExcel.GenerateWorksheet(objRS)If objExcel.SaveWorksheet(Server.MapPath(ExcelPath)) then "Response.Write "已保存为Excel文件.下载"ElseResponse.Write "在保存过程中有错误!"End IfSet objExcel = NothingobjRS.CloseSet objRS = Nothing%>二、用Excel的Application组件在客户端导出到Excel或Word 注意:两个函数中的“data“是网页中要导出的table的 id导出到Excel代码导出到Word代码三、直接在IE中打开,再存为EXCEL文件把读出的数据用格式,在网页中显示出来,同时,加上下一句即可把EXCEL表在客客户端显示。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
用模板生成Excel、Word最大优点:Word、Excel文档样式易于控制和调整,以往用Excel.Application来生成Excel、Word,需要写很多代码来控制排版的样式,用模版几乎不受任何限制,只需要打开word或Excel,编辑文档,选择"文件->另存为web页",即可方便的做好模板,用office生成的模板要比直接在DW中做好模板更加符合office偏好,生成后文件样式可与原word、Excel格式99%一样,因此建议大家用office(office97~office2003)直接来生成模板框架。
主要的代码function.asp复制内容到剪贴板代码:<%''开启容错机制on error resume next'功能,检测服务器是否支持指定组件Function object_install(strclassstring)on error resume nextobject_install=falsedim xtestobjset xtestobj=server.createobject(strclassstring)if -2147221005 <> Err then object_install=trueset xtestobj=nothingend functionif object_install("Scripting.FileSystemobject")=false thenResponse.Write "<div style='font-size:12px;color:#333;height:20px;line-height:20px;border:1px solid #DDCF8F;padding:6px;background:#FFFFED;font-family:verdana'>对不起,您的空间不支持FSO组件,请与管理员联系!</div>"Response.Endend ifif object_install("adodb.stream")=false thenResponse.Write "<div style='font-size:12px;color:#333;height:20px;line-height:20px;border:1px solid #DDCF8F;padding:6px;background:#FFFFED;font-family:verdana'>对不起,您的空间不支持adodb.stream功能,请与管理员联系!</div>"Response.Endend if'-----------------------------------------------------------------------------'函数名称:ReadTextFile'作用:利用AdoDb.Stream对象来读取文本文件'参数:FileUrl文件相对路径,FileCharSet:文件编码Function ReadFromTextFile (FileUrl,FileCharSet)'函数dim strset stm=server.CreateObject("adodb.stream")stm.Type=2 '指定或返回的数据类型,stm.mode=3 '指定打开模式,现在为可以读写模式,类似于word的只读或锁定功能stm.charset=FileCharSetstm.openstm.loadfromfile server.MapPath(FileUrl)str=stm.readtextReadFromTextFile=strEnd Function'----------------------------------------------------------------------------- '函数名称:WriteToTextFile'作用:利用AdoDb.Stream对象来写入文本文件sub WriteToTextFile(FileUrl,Str,FileCharSet) '方法set stm=server.CreateObject("adodb.stream")stm.Type=2stm.mode=3stm.charset=FileCharSetstm.openstm.WriteText strstm.SaveToFile server.MapPath(FileUrl),2stm.flushEnd sub'----------------------------------------------------------------------------- '功能:自动创建文件夹'创建一级或多级目录,可以创建不存在的根目录'参数:要创建的目录名称,可以是多级'返回逻辑值,True成功,False失败'创建目录的根目录从当前目录开始Function CreateMultiFolder(ByVal CFolder)Dim objFSO,PhCreateFolder,CreateFolderArray,CreateFolder Dim i,ii,CreateFolderSub,PhCreateFolderSub,BlInfoBlInfo = FalseCreateFolder = CFolderOn Error Resume NextSet objFSO = Server.CreateObject("Scripting.FileSystemObject") If Err ThenErr.Clear()Exit FunctionEnd IfCreateFolder = Replace(CreateFolder,"","/")If Left(CreateFolder,1)="/" ThenCreateFolder = Right(CreateFolder,Len(CreateFolder)-1)End IfIf Right(CreateFolder,1)="/" ThenCreateFolder = Left(CreateFolder,Len(CreateFolder)-1)End IfCreateFolderArray = Split(CreateFolder,"/")For i = 0 to UBound(CreateFolderArray)CreateFolderSub = ""For ii = 0 to iCreateFolderSub = CreateFolderSub & CreateFolderArray(ii) & "/"NextPhCreateFolderSub = Server.MapPath(CreateFolderSub)If Not objFSO.FolderExists(PhCreateFolderSub) ThenobjFSO.CreateFolder(PhCreateFolderSub)End IfNextIf Err ThenErr.Clear()ElseBlInfo = TrueEnd IfCreateMultiFolder = BlInfoEnd Function'点击下载提示function downloadFile(strFile)strFilename = server.MapPath(strFile)Response.Buffer = TrueResponse.ClearSet s = Server.CreateObject("ADODB.Stream")s.Opens.Type = 1on error resume nextSet fso = Server.CreateObject("Scripting.FileSystemObject")if not fso.FileExists(strFilename) thenResponse.Write("<h1>Error:</h1>" & strFilename & " does not exist<p>")Response.Endend ifSet f = fso.GetFile(strFilename)intFilelength = f.sizes.LoadFromFile(strFilename)if err thenResponse.Write("<h1>Error: </h1>" & err.Description & "<p>")Response.Endend ifResponse.AddHeader "Content-Disposition", "attachment; filename=" & Response.AddHeader "Content-Length", intFilelengthResponse.CharSet = "UTF-8"Response.ContentType = "application/octet-stream"Response.BinaryWrite s.ReadResponse.Flushs.CloseSet s = NothingEnd Function'-----------------------------------------------------------------------------If Err Thenerr.ClearSet conn = NothingResponse.Write "<div style='font-size:12px;color:#333;height:20px;line-height:20px;border:1px solid #DDCF8F;padding:6px;background:#FFFFED;font-family:verdana'>网站异常出错,请与管理员联系,谢谢!</div>"Response.EndEnd If%>生成Word文档:复制内容到剪贴板代码:<%'创建文件dim templateName,templatechar,filepath,filename,fileCharset,templateContent templateName="template/template_word.htm" '模板名字,支持带路径,如"/moban/moban1.htm"或"temp/moban1.htm"templatechar="gb2312" '模板文本的编码filepath="files/word/" '生成文件保存的路径,当前目录请留空,其他目录,路径必须以“/”结尾filename="Doc1.doc" '即将生成的文件名CreateMultiFolder(filepath) '这一句用来判断文件夹是否存在,没有则自动创建,支持n级目录fileCharset="gb2312" '打算生成的文本编码'读取指定的模板内容templateContent=ReadFromTextFile(templateName,templatechar)'以下就交给你来替换模板内容了templateContent=replace(templateContent,"{$websiteName}","蓝色理想")templateContent=replace(templateContent,"{$userName}","幸福的子弹")templateContent=replace(templateContent,"{$now}",Now())'其他内容......'最终调用函数来生成文件Call WriteToTextFile(filepath&filename,templateContent,fileCharset)'最后关闭adodb.stream对象stm.flushstm.Closeset stm=nothingdownloadFile(filepath&filename)%>生成Excel文档:复制内容到剪贴板代码:<%'创建文件dim templateName,templatechar,filepath,filename,fileCharset,templateContent templateName="template/template_excel.htm" '模板名字,支持带路径,如"/moban/moban1.htm"或"temp/moban1.htm"templatechar="gb2312" '模板文本的编码filepath="files/excel/" '生成文件保存的路径,当前目录请留空,其他目录,路径必须以“/”结尾filename="Book1.xls" '即将生成的文件名CreateMultiFolder(filepath) '这一句用来判断文件夹是否存在,没有则自动创建,支持n级目录fileCharset="gb2312" '打算生成的文本编码'读取指定的模板内容templateContent=ReadFromTextFile(templateName,templatechar)'以下就交给你来替换模板内容了templateContent=replace(templateContent,"{$websiteName}","蓝色理想")templateContent=replace(templateContent,"{$userName}","幸福的子弹")templateContent=replace(templateContent,"{$now}",Now())'其他内容......'最终调用函数来生成文件Call WriteToTextFile(filepath&filename,templateContent,fileCharset)'最后关闭adodb.stream对象stm.flushstm.Closeset stm=nothingdownloadFile(filepath&filename)%>生成.htm静态页面复制内容到剪贴板代码:<%'创建文件dim templateName,templatechar,filepath,filename,fileCharset,templateContent templateName="template/template_html.htm" '模板名字,支持带路径,如"/moban/moban1.htm"或"temp/moban1.htm"templatechar="gb2312" '模板文本的编码filepath="files/html/" '生成文件保存的路径,当前目录请留空,其他目录,路径必须以“/”结尾filename="Untitled-1.htm" '即将生成的文件名CreateMultiFolder(filepath) '这一句用来判断文件夹是否存在,没有则自动创建,支持n级目录fileCharset="gb2312" '打算生成的文本编码'读取指定的模板内容templateContent=ReadFromTextFile(templateName,templatechar)'以下就交给你来替换模板内容了templateContent=replace(templateContent,"{$websiteName}","蓝色理想")templateContent=replace(templateContent,"{$userName}","幸福的子弹")templateContent=replace(templateContent,"{$now}",now())'其他内容......'最终调用函数来生成文件Call WriteToTextFile(filepath&filename,templateContent,fileCharset)'最后关闭adodb.stream对象stm.flushstm.Closeset stm=nothingresponse.Write("恭喜您,"&filename&"已经生成,<a href="""&filepath&filename&""" target=""_blank"">点击查看</a>")%>本文章来自 21视频教程网ASP+模板生成Word、Excel、静态页面的办法_Asp教程原文链接:/html/94166.shtml。