在ASP中怎么把页面中的数据导出到EXCEL
- 格式:rtf
- 大小:28.27 KB
- 文档页数:5
如何用asp把access中数据导出到excel表格中?ASP操作Excel技术总结目录一、环境配置二、ASP对Excel的基本操作三、ASP操作Excel生成数据表四、ASP操作Excel生成Chart图五、服务器端Excel文件浏览、下载、删除方案六、附录正文一、环境配置服务器端的环境配置从参考资料上看,微软系列的配置应该都行,即:1.Win9x+PWS+Office2.Win2000 Professional+PWS+Office3.Win2000 Server+IIS+Office目前笔者测试成功的环境是后二者。
Office的版本没有特殊要求,考虑到客户机配置的不确定性和下兼容特性,建议服务器端Office版本不要太高,以防止客户机下载后无法正确显示。
服务器端环境配置还有两个偶然的发现是:1.笔者开发机器上原来装有金山的WPS2002,结果Excel对象创建始终出现问题,卸载WPS2002后,错误消失。
2.笔者开发ASP代码喜欢用FrontPage,结果发现如果FrontPage打开(服务器端),对象创建出现不稳定现象,时而成功时而不成功。
扩展考察后发现,Office系列的软件如果在服务器端运行,则Excel 对象的创建很难成功。
服务器端还必须要设置的一点是COM组件的操作权限。
在命令行键入“DCOMCNFG”,则进入COM组件配置界面,选择Microsoft Excel后点击属性按钮,将三个单选项一律选择自定义,编辑中将Everyone 加入所有权限。
保存完毕后重新启动服务器。
客户端的环境配置没发现什么特别讲究的地方,只要装有Office和IE即可,版本通用的好象都可以。
二、ASP对Excel的基本操作1、建立Excel对象set objExcelApp = CreateObject("Excel.Application")objExcelApp.DisplayAlerts = false不显示警告objExcelApp.Application.Visible = false不显示界面2、新建Excel文件objExcelApp.WorkBooks.addset objExcelBook = objExcelApp.ActiveWorkBookset objExcelSheets = objExcelBook.Worksheetsset objExcelSheet = objExcelBook.Sheets(1)3、读取已有Excel文件strAddr = Server.MapPath(".")objExcelApp.WorkBooks.Open(strAddr & "\Templet\Table.xls")set objExcelBook = objExcelApp.ActiveWorkBookset objExcelSheets = objExcelBook.Worksheetsset objExcelSheet = objExcelBook.Sheets(1)4、另存Excel文件objExcelBook.SaveAs strAddr & "\Temp\Table.xls"5、保存Excel文件objExcelBook.Save(笔者测试时保存成功,页面报错。
本篇中将简单记录下Aspose.Cells这个强大的Excel操作组件。
这个组件的强大之处,就不多说,对于我们的报表总是会有导出Excel的处理,如果你使用微软Excel的com组件,那么对于简单的操作还行,但是多余复杂的模板,那将是一个令人头疼的事。
在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))还有其他更为复杂的汇总计算的表达式,这里也不在这节多讲,有兴趣的朋友,可以去官网看看。
我们先来个简单的例子,光说,总是不行的,还是要代码实践才能说明一切:Excel模板1:代码:在我们的代码中添加数据源:如下:View Code1var sql = @"select * from Customers2 where Customers.City ='London'";3 var dt=GetDataTable(sql);4 dt.TableName = "Customers";5 WorkbookDesigner designer = new WorkbookDesigner();6 designer.Open(MapPath("~/1.xls"));7//数据源8 designer.SetDataSource(dt);9//报表单位10 designer.SetDataSource("ReportUtils", "xxxxx有限公司客户信息");11 designer.SetDataSource("ReportAdd", "London");12//截止日期13 designer.SetDataSource("ReportDate", DateTime.Now.ToString("yyyy年MM月dd日"));1415 designer.Process();1617 designer.Save(string.Format("report.xls"), SaveType.OpenInExcel, FileFormatType.E xcel2003, Response);18 Response.Flush();19 Response.Close();20 designer = null;21 Response.End();代码很简单,就是添加了一个datatable,和几个变量的数据源,我们所生成excel为:这就完成了我们的一个简单的多表头数据导出报表。
Core导⼊导出Excelxlsx⽂件实例 Core 使⽤EPPlus.Core导⼊导出Excel xlsx ⽂件,EPPlus.Core⽀持Excel 2007/2010 xlsx⽂件导⼊导出,可以运⾏在Windows, Linux和Mac。
EPPlus.Core 是基于EPPlus 更改⽽来,在Linux 下需要安装libgdiplus 。
下⾯在 Core 中导⼊导出Excel xlsx ⽂件。
新建项⽬新建⼀个 Core Web Application 项⽬ASPNETCoreExcel,选择Web 应⽤程序不进⾏⾝份验证。
然后添加EPPlus.Core 引⽤。
使⽤NuGet 命令⾏:Install-Package EPPlus.Core也可以使⽤NuGet包管理器安装。
导出xlsx⽂件新建⼀个XlsxController ,添加Export 操作。
public class XlsxController : Controller{private IHostingEnvironment _hostingEnvironment;public XlsxController(IHostingEnvironment hostingEnvironment){_hostingEnvironment = hostingEnvironment;}public IActionResult Index(){return View();}public IActionResult Export(){string sWebRootFolder = _hostingEnvironment.WebRootPath;string sFileName = $"{Guid.NewGuid()}.xlsx";FileInfo file = new FileInfo(bine(sWebRootFolder, sFileName));using (ExcelPackage package = new ExcelPackage(file)){// 添加worksheetExcelWorksheet worksheet = package.Workbook.Worksheets.Add("aspnetcore");//添加头worksheet.Cells[1, 1].Value = "ID";worksheet.Cells[1, 2].Value = "Name";worksheet.Cells[1, 3].Value = "Url";//添加值worksheet.Cells["A2"].Value = 1000;worksheet.Cells["B2"].Value = "LineZero";worksheet.Cells["C2"].Value = "/linezero/";worksheet.Cells["A3"].Value = 1001;worksheet.Cells["B3"].Value = "LineZero GitHub";worksheet.Cells["C3"].Value = "https:///linezero";worksheet.Cells["C3"].Style.Font.Bold = true;package.Save();}return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");}}通过依赖注⼊获取HostingEnvironment,对应可以获取程序的相关⽬录及属性。
网页数据如何简单导出excel在浏览网页时,遇到我们需要的网页数据时,如文字、图片等,如何能简单的导出到Excel 中,方便在本地电脑中查看和编辑呢?当然是有办法的啦!下面就为大家介绍几种简单快速的将网页数据导出到Excel的方法,大家可以灵活运用。
一、通过浏览器导出网页数据具体操作:打开某网页后,右键点击网页空白处,在下拉列表中选择“另存为”,然后在弹出的保存窗口中选择保存类型为“网页全部”。
选择保存位置后确定,保存后就会自动保存两个文件,一个是网址,另一个是保存网页内容元素。
如何导出网页数据,以赶集网采集为例图1二、通过网页数据采集器导出网页数据先通过网页数据采集器,将网页数据采集下来,然后再导出为需要的格式即可。
本文使用的是操作简单、功能强大的八爪鱼采集器。
以下是一个八爪鱼采集并导出网页数据的完整示例。
示例中采集的是赶集网上房产-商铺-深圳-南山分类下的所有商铺信息。
示例网站:/fang6/nanshan/步骤1:创建采集任务1)进入主界面,选择“自定义模式”如何导出网页数据,以赶集网采集为例图22)将要采集的网址URL,复制粘贴到网址输入框中,点击“保存网址”如何导出网页数据,以赶集网采集为例图3步骤2:创建翻页循环1)在页面右上角,打开“流程”,以展现出“流程设计器”和“定制当前操作”两个板块。
将页面下拉到底部,点击“下一页”按钮,在右侧的操作提示框中,选择“循环点击下一页”如何导出网页数据,以赶集网采集为例图4步骤3:创建列表循环1)移动鼠标,选中页面里的第一个商铺链接。
选中后,系统会自动识别页面里的其他相似链接。
在右侧操作提示框中,选择“选中全部”如何导出网页数据,以赶集网采集为例图52)选择“循环点击每个链接”,以创建一个列表循环如何导出网页数据,以赶集网采集为例图6步骤4:提取商铺信息1)在创建列表循环后,系统会自动点击第一个商铺链接,进入商铺详细信息页。
点击需要的字段信息,在右侧的操作提示框中,选择“采集该元素的文本”如何导出网页数据,以赶集网采集为例图72)字段信息选择完成后,选中相应的字段,可以进行字段的自定义命名。
Aspose.cell中的Excel模板导出数据//Excel模板导数据(Eexcel中根据DataTable中的个数,给多个Sheet中的模板赋值) dict中模板设置 &=$qyear datatable中设置 &=dtName.cloumnName public void DataSetToManyExcel(string fileName, string fileUrl, Page page, DataSet my_ds, Dictionary<string, string> dict = null, params int[] columns){WorkbookDesigner wbookdesiger = new WorkbookDesigner();wbookdesiger.Open(fileUrl); //打开模板try{if (my_ds.Tables.Count > 0){for (var i = 0; i < my_ds.Tables.Count; i++){//设置DataTablewbookdesiger.SetDataSource(my_ds.Tables[i]);//设置变量if (dict != null){foreach (var di in dict)wbookdesiger.SetDataSource(di.Key, di.Value);}wbookdesiger.Process(i, false);//清除数据源wbookdesiger.ClearDataSource();} if (columns.Length > 0) { Style style = wbookdesiger.Workbook.Styles[wbookdesiger.Workbook.Styles.Add()];//新增样式 style.IsTextWrapped = true;//⽂本换⾏样式\n columns.ForEach(c => { var cells = wbookdesiger.Workbook.Worksheets[0].Cells[c]; cells.SetStyle(style); }); }fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls";wbookdesiger.Save(fileName, SaveType.OpenInExcel, FileFormatType.Excel2003, page.Response);page.Response.End();}}catch (Exception ex){throw ex;}}//Excel模板导数据(Eexcel中根据DataTable中的个数,复制第⼀个Sheet中的模板,然后分别赋值)public void DataSetToOneExcel(string fileName, string fileUrl, Page page, DataSet my_ds, string tabName = "", Dictionary<int, string> my_dic = null){WorkbookDesigner my_designer = new WorkbookDesigner();my_designer.Open(fileUrl);//打开⽂件Workbook my_workbook = my_designer.Workbook;try{if (my_ds.Tables.Count > 0){//给表格赋值for (var i = 0; i < my_ds.Tables.Count; i++){var temp = i + 1 >= my_ds.Tables.Count ? i : i + 1;//TableNameif (i == 0)my_ds.Tables[i].TableName = tabName != "" ? tabName : "dt";elsemy_ds.Tables[temp].TableName = tabName != "" ? tabName + i : "dt" + temp;my_workbook.Worksheets.AddCopy(0);//复制前⼀个Sheet模板my_workbook.Worksheets[i + 1].Replace(my_ds.Tables[0].TableName, my_ds.Tables[temp].TableName);//替换当前Sheet的下个Sheet的TableName my_designer.SetDataSource(my_ds.Tables[i]);my_designer.Process(i, false);my_designer.ClearDataSource();}//删除最后⼀个sheetmy_workbook.Worksheets.RemoveAt(my_workbook.Worksheets.Count - 1);//给Sheet的Name赋值if (my_dic != null){for (var i = 0; i < my_workbook.Worksheets.Count; i++){foreach (var dd in my_dic){if (i == dd.Key)my_workbook.Worksheets[i].Name = dd.Value;}}}fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls";my_designer.Save(fileName, SaveType.OpenInExcel, FileFormatType.Excel2003, page.Response);page.Response.End();}}catch (Exception ex){throw ex;}}补充:当表格数据列是动态的时候,显然模板就不⼤适⽤了,这时候我们可以使⽤Apose.Cells的填充⽅法Aspose.Cells.WorkbookDesigner wbookdesiger = new Aspose.Cells.WorkbookDesigner();wbookdesiger.Open(fileUrl); //打开模板//wbookdesiger.SetDataSource(dt);//wbookdesiger.Process();//数据渲染var workbook = wbookdesiger.Workbook;//最后合成⼀个DT来,⼀个合成的动态数据表Aspose.Cells.Cell cell = workbook.Worksheets[0].Cells.FindString("#$DATATABLE$#", null, true);//模板中的列,找出模板中固定的单元格if (cell != null){workbook.Worksheets[0].Cells.ImportDataTable(dt, true, );}int temp = 0; //合并单元格while (temp < dt.Rows.Count){var rows = dt.Select(" 序号=" + dt.Rows[temp]["序号"]);workbook.Worksheets[0].Cells.Merge(1 + temp, 0, rows.Length, 1);workbook.Worksheets[0].Cells.Merge(1 + temp, 1, rows.Length, 1);workbook.Worksheets[0].Cells.Merge(1 + temp, 2, rows.Length, 1);workbook.Worksheets[0].Cells.Merge(1 + temp, 3, rows.Length, 1);workbook.Worksheets[0].Cells.Merge(1 + temp, 4, rows.Length, 1);workbook.Worksheets[0].Cells.Merge(1 + temp, 11, rows.Length, 1);workbook.Worksheets[0].Cells.Merge(1 + temp, 12, rows.Length, 1);workbook.Worksheets[0].Cells.Merge(1 + temp, 13, rows.Length, 1);temp += rows.Length;}var sheet = workbook.Worksheets[0];var cells = sheet.Cells;int columnCount = cells.MaxColumn; //获取表页的最⼤列数int rowCount = cells.MaxRow; //获取表页的最⼤⾏数//适应列宽for (int col = 0; col < columnCount; col++){sheet.AutoFitColumn(col, 0, rowCount);}for (int col = 0; col < columnCount; col++){cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 30);}//表格线Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];style.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = Aspose.Cells.CellBorderType.Thin;style.Borders[Aspose.Cells.BorderType.TopBorder].Color = System.Drawing.Color.Black;style.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle =Aspose.Cells. CellBorderType.Thin;style.Borders[Aspose.Cells.BorderType.BottomBorder].Color = System.Drawing.Color.Black;style.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = Aspose.Cells.CellBorderType.Thin;style.Borders[Aspose.Cells.BorderType.LeftBorder].Color = System.Drawing.Color.Black;style.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle =Aspose.Cells.CellBorderType.Thin;style.Borders[Aspose.Cells.BorderType.RightBorder].Color = System.Drawing.Color.Black;Aspose.Cells.Range wstrange = sheet.Cells.CreateRange(0, 0, sheet.Cells.MaxRow + 1, sheet.Cells.MaxColumn + 1);Aspose.Cells.StyleFlag stFlag = new Aspose.Cells.StyleFlag();stFlag.All = true;wstrange.ApplyStyle(style, stFlag);var stream = workbook.SaveToStream();return File(stream.ToArray(), "application/octet-stream", "xxxx.xls");。
将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文件 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>。
⽣成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文件 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>。