asp导入word和excel
- 格式:docx
- 大小:13.04 KB
- 文档页数:2
⽤Aspose.Words从Word⽂档中提取表格数据对于某些项⽬,开发⼈员需要从Word⽂档中提取数据并导出到数据库。
最⼤的挑战是必须⽀持现有Word⽂档。
相同格式且带多个数据块的Word⽂档有成千上万。
该⽂档格式并不是设计来被另⼀个系统所读取的。
这意味着,没有书签、合并字段、从标准指令识别实际数据的⽅式等。
还好,所有输⼊字段都在表格内,但这些表格也是不同的格式,⼀些是单⾏/单元格,另⼀些则变化多端。
我们可以⽤来创建和操作Word⽂档。
以C#创建⼀个类似的表格模型从⽽稍后当读取⽂档的时候我们可以⽤上它。
如下所⽰,你可以看到创建的名为WordDocumentTable的类,带有三个属性:TableID,RowID和ColumnID,如之前所说的,我们没有⽀持TableID/RowIDs,这些属性仅仅暗⽰着Word⽂档的位置。
开始索引假定为0。
public class WordDocumentTable{public WordDocumentTable(int PiTableID){MiTableID = PiTableID;}public WordDocumentTable(int PiTableID, int PiColumnID){MiTableID = PiTableID;MiColumnID = PiColumnID;}public WordDocumentTable(int PiTableID, int PiColumnID, int PiRowID){MiTableID = PiTableID;MiColumnID = PiColumnID;MiRowID = PiRowID;}private int MiTableID = 0;public int TableID{get { return MiTableID; }set { MiTableID = value; }}private int MiRowID = 0;public int RowID{get { return MiRowID; }set { MiRowID = value; }}private int MiColumnID = 0;public int ColumnID{get { return MiColumnID; }set { MiColumnID = value; }}}现在来到提取环节。
竭诚为您提供优质文档/双击可除asp插入表格篇一:javascript动态添加表格数据行,asp后台数据库保存例子在很多web应用中,我们会遇到很多需要动态插入多行纪录的地方。
比如,在人才网站上,我们填写简历的时候,我们要填写我们的项目经验,我们可以根据自己的实际情况动态的添加条数,这种不是以单独页面的形式添加,这种动态添加是在同一个页面下动态添加,最后再一起提交到服务器保存到数据库中。
本文,我将以一个类似的例子来做一个前台用javascript动态添加数据项,后台保存到数据库的例子。
浏览器:ie.6.0后台:asp(Vbscript)前台:html+javascripthtml代码:name:sex:projectname: befredescription: begindate: Finisheddate: deletejs代码:/*thisfunctionisusetoaddonerowdynamicly*tabobj:targettable*colnum:thenumberofcolumnsthatofarowintable*sorpos:thesourceofthenewrow.*targpos:thepositionwherethenewrowwillbeadded.**/functionaddRow(tabobj,colnum,sorpos,targpos){varntR=tabobj.insertRow(tabobj.rows.length-targpos) ;//insertanewrowintoappointedtableonthe//appointedposition.vartRs=tabobj.getelementsbytagname(tR);//gettRscoll ectionfromtheappointedtablevarsortR=tRs[sorpos];//positionedthesortRvartds=sortR.getelementsbytagname(td);//gettdscolle ctionfromtheappointedrowif(colnum==0||colnum==undefined||colnum==isnan){ colnum=tabobj.rows[0].cells.length;}varntd=newarray();//createanewtdsarrayfor(vari=0;i//suffixmustbeappointedntd[i].innerhtml=tds[i].innerhtml;//copythevalueinn td[i]sinnerhtmlfromcorrespondingtds}}/*thisfunctionisusetoremoveappointedrowinappointedt able*tabobj:theappointedtable*targpos:targetrowposition*btnobj:currentlyclickeddeleteimagebutton**/functiondeleteRow(tabobj,targpos,btnobj){//Removeta blerowfor(vari=0;iif(tabobj.getelementsbytagname(img)[i]==btnobj){ tabobj.deleteRow(i+targpos);}}}前台代码总结:上面的代码有一个要注意的地方,那就是原始行,我们设置了样式为display:none,这是因为,下面js中添加行采用的是newtd.innerhtml=sourcetd.innerhtml的方式,即直接把已经存在的列中的内容直接复制到新添加的列的innerhtml属性中,所以隐藏“数据源“列被防止用户删除而出现"objectexcepted"错误。
使⽤Aspose插件对Excel操作使⽤使⽤Aspose插件对Excel⽂档进⾏导⼊导出操作使⽤前请先下载Aspose插件引⽤Excel导⼊:前台使⽤file标签获取,submit⽅式提交。
<form id="form1" enctype="multipart/form-data" method="post"><table class="table-condensed"><tr><td class="text-right">导⼊表格:</td><td class="text-left"><input type="file" name="file1" class="btn btn-default btn-lg"/></td></tr><tr><td class="text-left"><input type="submit" id="btnImport" name="btnImport" value="导⼊" class="btn btn-default"/></td></tr></table></form>后台接收:HttpPostedFileBase fileBase = Request.Files["file1"];//这⾥获取名称与前台标签name保持⼀致if (fileBase != null){string filename = Path.GetFileName(fileBase.FileName);string extension = Path.GetExtension(filename);string path = "/Upload/Test/" + DateTime.Now.ToString("yyyyMMdd") + "/";Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(path)));string newFilename = DateTime.Now.ToString("yyyyMMddHHmmssfff");string fullFileName = path + newFilename + extension;fileBase.SaveAs(Request.MapPath(fullFileName)); try{ Stopwatch sw = new Stopwatch();//记录导⼊操作⽤时多长sw.Start();//这⾥可放⼊BLL⽅法处理string result = new ProductBLL().ImportExcel(Request.MapPath(path), newFilename, extension);//BLL⽅法 ProductBLLpublic string ImportExcel(string path, string filename, string extension){Workbook workbook = new Workbook(path + filename + extension);Worksheet worksheet = workbook.Worksheets[0];Cells cells = worksheet.Cells;for (int i = 1; i < cells.Rows.Count; i++){try{string brand = cells[i, 0].StringValue.Trim();//获取列值string years = cells[i, 1].StringValue.Trim();}catch (Exception e){continue;}}return "OK";} sw.Stop();long runTime = sw.ElapsedMilliseconds / 1000; //获取到操作⽤时多少秒 } catch (Exception e){Log.Write("导⼊", "导⼊错误", "错误信息:" + e.Message);}}Excel导出:string path = "/Upload/Test/" + DateTime.Now.ToString("yyyyMMdd") + "/";Directory.CreateDirectory(Path.GetDirectoryName(Server.MapPath(path)));string newFilename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls";string fullFileName = Server.MapPath(path + newFilename);public void ExportInfo(List<Test> list, string fullFileName){Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();Aspose.Cells.Worksheet cellSheet = workbook.Worksheets[0];cellSheet.PageSetup.LeftMargin = 0.3;//左边距cellSheet.PageSetup.RightMargin = 0.3;//右边距cellSheet.PageSetup.TopMargin = 1;//上边距cellSheet.PageSetup.BottomMargin = 0.5;//下边距cellSheet.PageSetup.FooterMargin = 0.5;//页脚cellSheet.PageSetup.HeaderMargin = 0.5;//页眉cellSheet.PageSetup.Orientation = ndscape;cellSheet.PageSetup.CenterHorizontally = true;//⽔平居中cellSheet.PageSetup.CenterVertically = true;cellSheet.Cells[0, 0].PutValue("货号");cellSheet.Cells[0, 1].PutValue("颜⾊");cellSheet.Cells[0, 2].PutValue("尺码");int i = 1;foreach (var item in list){cellSheet.Cells[i, 0].PutValue(item.productno);cellSheet.Cells[i, 1].PutValue(item.size);cellSheet.Cells[i, 2].PutValue(item.color);i++;}cellSheet.AutoFitColumns();fullFileName = Path.GetFullPath(fullFileName);workbook.Save(fullFileName);}return File(fullFileName, "application/ms-excel", UserName + "_Test单" + newFilename);// ⽅法Action⾥直接返回File⽂件下载。
使用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>。
Aspose.Words使用代码插入表格Aspose.Words是一款功能强大的word文档处理控件,在不需要安装word的条件下,可进行word的创建,修改,转换等操作。
Aspose.Words可以简单使用该产品提供的DocumentBuilder类库进行Word表格的插入。
DocumentBuilder.StartTable 开始构建一个新的表格DocumentBuilder.InsertCell 插入新的行和单元格到表格DocumentBuilder.Writeln 为当前单元格写入文本DocumentBuilder.EndRow用于指示结束当前行,并且开始新的一行DocumentBuilder.EndTable 表示表格构建完成下面的代码,展示了如何插入一个简单无格式的表格到word:Document doc = new Document();DocumentBuilder builder = new DocumentBuilder(doc);// We call this method to start building the table.builder.StartTable();builder.InsertCell();builder.Write("Row 1, Cell 1 Content.");// Build the second cellbuilder.InsertCell();builder.Write("Row 1, Cell 2 Content.");// Call the following method to end the row and start a new row.builder.EndRow();// Build the first cell of the second row.builder.InsertCell();builder.Write("Row 2, Cell 1 Content");// Build the second cell.builder.InsertCell();builder.Write("Row 2, Cell 2 Content.");builder.EndRow();// Signal that we have finished building the table.builder.EndTable();// Save the document to disk.doc.Save(MyDir + "DocumentBuilder.CreateSimpleT able Out.doc");下面代码展示了,如何使用代码插入格式化的表格到word:Document doc = new Document();DocumentBuilder builder = new DocumentBuilder(doc);Table table = builder.StartTable();// Make the header row.builder.InsertCell();// Set the left indent for the table. Table wide formatting must be applied after// at least one row is present in the table.table.LeftIndent = 20.0;// Set height and define the height rule for the header row.builder.RowFormat.Height = 40.0;builder.RowFormat.HeightRule = HeightRule.AtLeast;// Some special features for the header row.builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;builder.Font.Size = 16;/doc/c610264504.html, = "Arial";builder.Font.Bold = true;builder.CellFormat.Width = 100.0;builder.Write("Header Row,\n Cell 1");// We don't need to specify the width of this cell because it's inherited from the previous cell.builder.InsertCell();builder.Write("Header Row,\n Cell 2");builder.InsertCell();builder.CellFormat.Width = 200.0;builder.Write("Header Row,\n Cell 3");builder.EndRow();// Set features for the other rows and cells.builder.CellFormat.Shading.BackgroundPatternColor =Color.White;builder.CellFormat.Width = 100.0;builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;// Reset height and define a different height rule for table bodybuilder.RowFormat.Height = 30.0;builder.RowFormat.HeightRule= HeightRule.Auto;builder.InsertCell();// Reset font formatting.builder.Font.Size = 12;builder.Font.Bold = false;// Build the other cells.builder.Write("Row 1, Cell 1 Content");builder.InsertCell();builder.Write("Row 1, Cell 2 Content");builder.InsertCell();builder.CellFormat.Width = 200.0;builder.Write("Row 1, Cell 3 Content");builder.EndRow();builder.InsertCell();builder.CellFormat.Width = 100.0;builder.Write("Row 2, Cell 1 Content");builder.InsertCell();builder.Write("Row 2, Cell 2 Content");builder.InsertCell();builder.CellFormat.Width = 200.0;builder.Write("Row 2, Cell 3 Content.");builder.EndRow();builder.EndTable();doc.Save(MyDir + "DocumentBuilder.CreateFormattedT able Out.doc");。
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表在客客户端显示。
201412261323_ASP导入Excel表格导入EXCEL表格常用于批处理数据或者数据迁移项目。
导入代码如下:<!--#include file="conn.asp" --><%Set ConnExcel=Server.CreateObject("ADODB.Connection")'--利用Open 方法打开数据库StrExcelConn="Driver={Microsoft Excel Driver (*.xls)};"&"DriverId=790; DBQ="&Server.MapPath("card.xls") 'EXCEL文件路径ConnExcel.Open StrExcelConn'--建立数据集对象Rs并查询数据Set Rs = Server.CreateObject("ADODB.Recordset")Sql="select * from [default$]" '特别注意EXCEL表名要一致rs.Open Sql,ConnExcel,1,1do while not rs.eofrsx=server.createobject("adodb.recordset")setsqlx="select * from pcard"sqlx,conn,1,3rsx.openrsx.addnewrsx("cardnum")=rs(0)rsx("cardpwd")=rs(1)rsx("cardpay")=cint(rs(2))rsx.updatersx.closersx=nothingsetrs.MoveNextlooprs.closeset rs=nothingConnExcel.closeset ConnExcel=nothingCall Closeconn()response.write "<script language=JavaScript>"response.Write "alert('导入成功!'); "response.Write "</script>"Response.end()%>人生最精彩的不是实现梦想的瞬间,而是坚持梦想的过程。
C#Aspose.Words数据写⼊到Word⼀、通过“域”写⼊数据在Word中,打开【插⼊】选项卡——【⽂档部件】——【域】,在【域】的功能对话框中,可以看到有全部、编号、等式和公式等多种类别,通过选择这些类别,可以使⽤域来进⾏⾃动更新的相关功能。
包括公式计算、变化的时间⽇期、邮件合并等。
除了利⽤上述步骤插⼊域外,也可以按Ctrl+F9⼿⼯输⼊域。
域实际上是Word中的代码,按Shift+F9可以在代码与计算结果之间进⾏切换。
此处不理解也没关系,看下⾯例⼦就可以了。
“《》”并不是⾃⼰⼿动打出来的,要通过⽂本域构建插⼊⽂本域。
(插⼊--->⽂档部件--->域---->选择MergeFileID--->填写域名---->点击保存)按Alt + F9 是这个样⼦的这个“域”可以通过我们后台代码动态的显⽰我们需要的值,⽐如说《Name》想要变成 Name:Ramon ,Title:《Title》变成 Ramon Title ⼆、代码实现1.在实现的同时我们也需要准备好Aspose.Words.dll 破解版可以上⽹找....2.如果不是破解版他会有⽔印和⾃动⽣成的表头和底部信息(商⽤还是⽤正版吧)添加⼀个AsposeWordHelper帮助类using Aspose.Words;using Aspose.Words.Drawing;using System;using System.Collections.Generic;using System.Data;using System.IO;using ;using .Http;using .Http.Headers;namespace WordHelper{/// <summary>/// word⽂档操作辅助类/// </summary>public class AsposeWordHelper{/// <summary>/// Word/// </summary>private Document _doc;private string _tempPath;private SaveFormat _saveFormat;/// <summary>////// </summary>/// <param name="tempPath">模板地址</param>/// <param name="saveFormat">转换后的类型</param>public AsposeWordHelper(string tempPath, SaveFormat saveFormat = SaveFormat.Doc){this._tempPath = tempPath;this._saveFormat = saveFormat;}/// <summary>/// ⽂本域处理泛型集合赋值/// </summary>/// <typeparam name="TEntity"></typeparam>/// <param name="entity"></param>public void Execute<TEntity>(TEntity entity){var type = entity.GetType();var properties = type.GetProperties();List<string> names = new List<string>();List<string> values = new List<string>();foreach (var item in properties){names.Add();values.Add(item.GetValue(entity, null).ToString());}_doc.MailMerge.Execute(names.ToArray(), values.ToArray());}/// <summary>/// ⽂本域处理键值对赋值/// </summary>/// <param name="entity"></param>public void Execute(Dictionary<string, string> entity){List<string> names = new List<string>();List<string> values = new List<string>();foreach (var item in entity)names.Add(item.Key);values.Add(item.Value);}_doc.MailMerge.Execute(names.ToArray(), values.ToArray());}/// <summary>/// 保存/// </summary>/// <param name="filePath"></param>public void Save(string filePath){_doc.Save(filePath, _saveFormat);}/// <summary>/// 基于模版新建Word⽂件/// </summary>/// <param name="path">模板路径</param>public void OpenTempelte(){_doc = new Document(_tempPath);}/// <summary>/// 书签赋值⽤法/// </summary>/// <param name="LabelId">书签名</param>/// <param name="Content">内容</param>public void WriteBookMark(string LabelId, string Content){if (_doc.Range.Bookmarks[LabelId] != null){_doc.Range.Bookmarks[LabelId].Text = Content;}}/// <summary>/// 列表赋值⽤法/// </summary>/// <param name="dt"></param>public void WriteTable(DataTable dt){_doc.MailMerge.ExecuteWithRegions(dt);}/// <summary>/// 不可编辑受保护,需输⼊密码/// </summary>/// <param name="pwd">密码</param>public void NoEdit(string pwd){_doc.Protect(ProtectionType.ReadOnly, pwd);}/// <summary>/// 只读/// </summary>public void ReadOnly(){_doc.Protect(ProtectionType.ReadOnly);}/// <summary>/// 添加图⽚/// </summary>/// <param name="filename">⽂件路径+⽂件名</param>/// <param name="field">⽂本域名</param>/// <param name="width">宽</param>/// <param name="height">⾼</param>public void AddImage(string filename, string field, double width = 70, double height = 70){DocumentBuilder builder = new DocumentBuilder(_doc);Shape shape = new Shape(_doc, ShapeType.Image);shape.ImageData.SetImage(filename);shape.Width = width;//设置宽和⾼shape.Height = height;shape.WrapType = WrapType.None;shape.BehindText = true;builder.MoveToMergeField(field);builder.InsertNode(shape);}/// <summary>/// 通过流导出word⽂件/// </summary>/// <param name="fileName">⽂件名</param>public HttpResponseMessage ExportWord(string fileName){var stream = new MemoryStream();_doc.Save(stream, SaveFormat.Doc);fileName += DateTime.Now.ToString("yyyyMMddHHmmss");HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);result.Content = new StreamContent(stream);result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/msword");result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = fileName + ".doc";return result;}/// <summary>/// 通过流导出pdf⽂件/// </summary>/// <param name="fileName">⽂件名</param>public HttpResponseMessage ExportPdf(string fileName){var stream = new MemoryStream();_doc.Save(stream, SaveFormat.Doc);fileName += DateTime.Now.ToString("yyyyMMddHHmmss");HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);result.Content = new StreamContent(stream);result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = fileName + ".pdf";return result;}}}using Aspose.Words;using Model.Model;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using WordHelper;namespace WordTest.App{class Program{private static readonly AsposeWordHelper _AsposeWordHelper;static Program() {_AsposeWordHelper = new AsposeWordHelper(@"C:\Users\NING MEI\Desktop\学习\test.docx");}static void Main(string[] args){//键值对_AsposeWordHelper.OpenTempelte(); //打开定义好的模板_AsposeWordHelper.Execute(new Dictionary<string, string>{{ "Name","Ramon"},{ "Title","Ramon Title"},}); //替换域赋值_AsposeWordHelper.ReadOnly();// 可以设为只读_AsposeWordHelper.Save(@"C:\Users\NING MEI\Desktop\学习\1.doc");//保存到哪个路径//泛型_AsposeWordHelper.OpenTempelte(); //打开定义好的模板_AsposeWordHelper.Execute(new ContractModel() {Name = "Ramon",Title = "RamonTitle"}); //替换域赋值_AsposeWordHelper.ReadOnly();// 可以设为只读_AsposeWordHelper.Save(@"C:\Users\NING MEI\Desktop\学习\2.doc");//保存到哪个路径}}}效果代码只是随便的写了下还有很多可以扩展的地⽅的,⼩编就懒得扩展了,这只是⼀个demo。
注意:两个函数中的“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 buildDoc
set table = document.all.data
row = table.rows.length
column = table.rows(1).cells.length
Set objWordDoc = CreateObject("Word.Document")
'objWordDoc.Application.Documents.Add theTemplate, False
objWordDoc.Application.Visible=True
Dim theArray(20,10000)
for i=0 to row-1
for j=0 to column-1
theArray(j+1,i+1) = table.rows(i).cells(j).innerTEXT
next
next
objWordDoc.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 With
Set rngCurrent = objWordDoc.Application.ActiveDocument.Paragraphs(3).Range
Set tabCurrent = ObjWordDoc.Application.ActiveDocument.Tables.Add(rngCurrent,row,column)
for i = 1 to column
objWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.InsertAfter
theArray(i,1)
objWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.ParagraphFormat.align ment=1
next
For i =1 to column
For j = 2 to row
objWordDoc.Application.ActiveDocument.Tables(1).Rows(j).Cells(i).Range.InsertAfter theArray(i,j) objWordDoc.Application.ActiveDocument.Tables(1).Rows(j).Cells(i).Range.ParagraphFormat.align ment=1
Next
Next
End Sub
</SCRIPT>。