ASP实现word输出代码

合集下载

ASP打印Word代码

ASP打印Word代码

//保证可以运行js的情况下<html><head><title>Build Document by Script</TITLE></HEAD><Table id="myData" border=1 align=center><Tr align=center><Td>列表1</Td><Td>列表2</Td><Td>列表3</Td></Tr><Tr align=center><Td>产品一</Td><Td>This is a test</Td><Td align=right>300.50</Td></Tr><Tr align=center><Td>产品二</Td><Td>This is a test</Td><Td align=right>300.50</Td></Tr><Tr align=center><Td>产品三</Td><Td>This is a test</Td><Td align=right>300.50</Td></Tr></Tabld><input type=button onclick="vbscript:buildDoc '',4" value="build"> <BODY></BODY></HTML><script language="vbscript">Sub buildDoc(theTemplate,intTableRows)Dim Table1set Table1 = document.all.myDatarow = Table1.rows.lengthSet objWordDoc = CreateObject("Word.Document")ObjWordDoc.Application.Visible=TrueDim theArray(4,4)'Redim Preserve theArray(4,row)colnum = Table1.rows(1).cells.lengthfor i=0 to row-1for j=0 to colnum-1theArray(j+1,i+1) = Table1.rows(i).cells(j).innerHTMLnextnextintNumrows = 4objWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertBefore("测试的表格")objWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertBefore("")objWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertBefore("")Set rngPara = objWordDoc.Application.ActiveDocument.Paragraphs(1).RangeWith rngPara.Bold = True.ParagraphFormat.Alignment = 1 = "Arial".Font.Size = 12End WithSet rngCurrent = objWordDoc.Application.ActiveDocument.Paragraphs(3).RangeSet tabCurrent = ObjWordDoc.Application.ActiveDocument.Tables.Add(rngCurrent,intNumrows,4) for i = 1 to colnumobjWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.InsertAfter theArray(i,1)objWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.ParagraphFormat.ali gnment=1nexttabRow = 2For j = 2 to intNumrows'ObjWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Borders.Enable=FalseobjWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(1).Range.InsertAfter theArray(1,j)objWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(1).Range.ParagraphFor mat.alignment=1objWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(2).Range.InsertAfter theArray(2,j)objWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(2).Range.ParagraphFor mat.alignment=1objWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(3).Range.InsertAfter FormatCurrency(theArray(3,j))objWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(3).Range.ParagraphFor mat.alignment=2objWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(4).Range.InsertAfter theArray(4,j)'objWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(4).Range.InsertAfter Chr(10)objWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(4).Range.ParagraphFor mat.alignment=1tabRow = tabRow + 1Next' objWordDoc.Application.ActiveDocument.Tables(1).Rows(tabRow).Cells(4).Range.ParagraphFor mat.alignment=1'objWordDoc.Application.ActiveDocument.Paragraph.Add.Range.InsertAfter(" ")'objWordDoc.Application.ActiveDocument.Paragraph.Add.Range.InsertAfter(" ")'objWordDoc.Application.ActiveDocument.Paragraph.Add.Range.InsertAfter("Regards,") 'objWordDoc.Application.ActiveDocument.Paragraph.Add.Range.InsertAfter(" ") 'objWordDoc.Application.ActiveDocument.Paragraph.Add.Range.InsertAfter("Daryl B. Morticum")'objWordDoc.Application.ActiveDocument.Paragraph.Add.Range.InsertAfter("Sales Associate")'objWordDoc.Application.ActiveDocument.Envelope.Insert Address' objWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertAfter("由廖家远设计")objWordDoc.Application.ActiveDocument.SaveAs "tempSample.doc", 0,False,"",True,"",False,False,False, False,False'objWordDoc.Application.printout()End Sub</script>更多信息请查看IT技术专栏。

Asp.netmvcword预览与打印

Asp.netmvcword预览与打印

mvcword预览与打印解决⽅案:1. 在后台把word⽂件转化成pdf,在前台⽤iframe显⽰pdf,打印iframe,即可。

优点:⽤户体验好。

缺点:不⽀持IE。

实现:引⽤netoffice组件主要代码:Word.Application wordApplication = new Word.Application();Word.Document pDoc = wordApplication.Documents.Open(path);pDoc.Activate();pDoc.SaveAs(pdf, WdSaveFormat.wdFormatPDF);wordApplication.Quit();wordApplication.Dispose();2. 在后台把word转化⾯html,读取html⽂本,增加打印脚本,输出到前台。

优点:浏览器⽀持的好。

缺点:⽤html显⽰word,不是太好看。

实现:引⽤:主要代码:public class WordToHtmlConverter{///<summary>/// Convert Docx to Html///</summary>///<param name="source">source file full name</param>///<returns>htmlstring</returns>public static string ToHtml(string source){var htmlString = string.Empty;var file = new FileInfo(source);byte[] bytes = File.ReadAllBytes(file.FullName);using (MemoryStream memoryStream = new MemoryStream()){memoryStream.Write(bytes, 0, bytes.Length);using (var wDoc = WordprocessingDocument.Open(memoryStream, true)){var imageFolder = source.Substring(0, source.Length - 5) + "_files";int imageCounter = 0;HtmlConverterSettings settings = new HtmlConverterSettings(){AdditionalCss = "body { margin: 1cm auto; max-width: 20cm; padding: 0; }",PageTitle = "新系统",FabricateCssClasses = true,CssClassPrefix = "pt-",RestrictToSupportedLanguages = false,RestrictToSupportedNumberingFormats = false,ImageHandler = imageInfo =>{DirectoryInfo localDirInfo = new DirectoryInfo(imageFolder);if (!localDirInfo.Exists)localDirInfo.Create();++imageCounter;string extension = imageInfo.ContentType.Split('/')[1].ToLower();ImageFormat imageFormat = null;if (extension == "png")imageFormat = ImageFormat.Png;else if (extension == "gif")imageFormat = ImageFormat.Gif;else if (extension == "bmp")imageFormat = ImageFormat.Bmp;else if (extension == "jpeg")imageFormat = ImageFormat.Jpeg;else if (extension == "tiff"){// Convert tiff to gif.extension = "gif";imageFormat = ImageFormat.Gif;}else if (extension == "x-wmf"){extension = "wmf";imageFormat = ImageFormat.Wmf;}// If the image format isn't one that we expect, ignore it,// and don't return markup for the link.if (imageFormat == null)return null;string imageFileName = imageFolder + "/image" +imageCounter.ToString() + "." + extension;try{imageInfo.Bitmap.Save(imageFileName, imageFormat);}catch (System.Runtime.InteropServices.ExternalException){return null;}string imageSource = + "/image" +imageCounter.ToString() + "." + extension;XElement img = new XElement(Xhtml.img,new XAttribute(NoNamespace.src, imageSource),imageInfo.ImgStyleAttribute,imageInfo.AltText != null ?new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);return img;}};XElement htmlElement = HtmlConverter.ConvertToHtml(wDoc, settings);// Produce HTML document with <!DOCTYPE html > declaration to tell the browser we are using HTML5.var html = new XDocument(new XDocumentType("html", null, null, null), htmlElement);htmlString = html.ToString(SaveOptions.DisableFormatting);}}return htmlString;}}public string NoticePrint(NoticeResult model){// 第⼀步,⽣成新的doc⽂档,替换模板⽂件中的标签,这⾥⽤的是NPOI,这个⽅法就不显⽰了,没什么东西。

springboot实现自动输出word文档功能的实例代码

springboot实现自动输出word文档功能的实例代码

springboot实现⾃动输出word⽂档功能的实例代码spring boot实现⾃动输出word⽂档功能本⽂⽤到Apache POI组件组件依赖在pom.xml⽂件中添加<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.0</version></dependency>⾸先创建相关的实体类、编写需要⽤到的sql查询。

import lombok.Data;// 选择题实体@Datapublic class MultiQuestion {private Integer questionId;private String subject;private String section;private String answerA;private String answerB;private String answerC;private String answerD;private String question;private String level;private String rightAnswer;private String analysis; //题⽬解析private Integer score;}import lombok.Data;//填空题实体类@Datapublic class FillQuestion {private Integer questionId;private String subject;private String question;private String answer;private Integer score;private String level;private String section;private String analysis; //题⽬解析}import lombok.Data;//判断题实体类@Datapublic class JudgeQuestion {private Integer questionId;private String subject;private String question;private String answer;private String level;private String section;private Integer score;private String analysis; //题⽬解析}创建好要⽤到的实体类之后,利⽤mybatis写sql查询,可以分为两种:1、配置mapper.xml⽂件路径,在xml⽂件中编写sql语句。

ASP导出为Word或Excel的最简单方法

ASP导出为Word或Excel的最简单方法

ASP导出为Word或Excel的最简单⽅法我在做⼀项⽬时,客户要求要将从数据库中获取数据后的ASP页⾯导出成EXCEL或WORD⽂档。

经本⼈试验后找出了最简单的⽅法:在ASP⽂件的最开头位置加⼊下⾯的代码就可以了,⾮常简单。

Asp代码1. EXCEL2. <%3. Response.ContentType ="application/vnd.ms-excel"4. Response.AddHeader "Content-Disposition", "attachment; filename=红宝⽹络表格.xls"5. %>6.7. WORD8. <%9. Response.ContentType ="application/vnd.ms-word"10. Response.AddHeader "Content-Disposition", "attachment; filename=红宝⽹络⽂档.doc"11. %>导出为WORD时,若⽂档中含有表格,需要打打印,则要在导出的页⾯中加⼊下⾯的样式。

Css代码1. <style type="text/css">2. <!--3. table{4. border-collapse:collapse;border:none;mso-border-alt:solid windowtext .5pt;5. mso-yfti-tbllook:480;mso-padding-alt:0cm 5.4pt 0cm 5.4pt;mso-border-insideh:6. .5pt solid windowtext;mso-border-insidev:.5pt solid windowtext;border-left:solid windowtext 1.0pt;border-top:solid windowtext 1.0pt;7. }8. td{9. border-top:none;border-left:10. none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;11. mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;12. mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;13. }14. -->15. </style>我打字系统项⽬中的⼀个导出为EXCEL⽂件的实例代码如下:Asp代码1. <!--#include file="hbwlConfig.asp" -->2. <%Response.ContentType ="application/vnd.ms-excel"3. Response.AddHeader "Content-Disposition", "attachment; filename=chengji.xls"%>4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd">5. <html xmlns="/1999/xhtml">6. <head>7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />8. <title>打字成绩</title>9. <style type="text/css">10. .tableWg {border:1px solid #9bbde6;}11. .tableWg tr{text-align:center;}12. .tableWg td{ border-bottom:1px dotted #9bbde6; border-right:1px dotted #9bbde6;}13. </style>14. </head>15. <body>16. <%sql=session("chengjisql")17. response.Write hbwl.dbSelect(sql,0,1,"",0,"",0,"tableWg")%>18. </body>19. </html>20. <%set hbwl=nothing%>。

asp.net操作word模板

asp.net操作word模板

操作word模板主要有两个⽅法///<summary>///从源DOC⽂档复制内容返回⼀个Document类///</summary>///<param name="sorceDocPath">源DOC⽂档路径</param>///<returns>Document</returns>protected Document copyWordDoc(object sorceDocPath){object objDocType = WdDocumentType.wdTypeDocument;object type = WdBreakType.wdSectionBreakContinuous;//Word应⽤程序变量Word._Application wordApp;//Word⽂档变量Document newWordDoc;object readOnly = false;object isVisible = false;//初始化//由于使⽤的是COM库,因此有许多变量需要⽤Missing.Value代替wordApp = new Application();Object Nothing = System.Reflection.Missing.Value;newWordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);Word._Document openWord;openWord = wordApp.Documents.Open(ref sorceDocPath, ref Nothing, ref readOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref openWord.Select();openWord.Sections[1].Range.Copy();object start = 0;Range newRang = newWordDoc.Range(ref start, ref start);//插⼊换⾏符//newWordDoc.Sections[1].Range.InsertBreak(ref type);newWordDoc.Sections[1].Range.PasteAndFormat(WdRecoveryType.wdPasteDefault);openWord.Close(ref Nothing, ref Nothing, ref Nothing);return newWordDoc;}///<summary>///替换指定Document的内容,并保存到指定的路径///</summary>///<param name="docObject">Document</param>///<param name="savePath">保存到指定的路径</param>protected void ReplaceWordDocAndSave(Document docObject, object savePath, List<string> findText, List<string> replaceText){object format = WdSaveFormat.wdFormatDocument;object readOnly = false;object isVisible = false;//string strOldText = "{WORD}";//string strNewText = "替换后的⽂本";List<string> IListOldStr = findText;List<string> IListNewStr = replaceText;string[] newStr = IListNewStr.ToArray();int i = 0;Object Nothing = System.Reflection.Missing.Value;Word._Application wordApp = new Application();Word._Document oDoc = docObject;object FindText, ReplaceWith, Replace;object MissingValue = Type.Missing;foreach (string str in IListOldStr){oDoc.Content.Find.Text = str;//要查找的⽂本FindText = str;//替换⽂本//ReplaceWith = strNewText;ReplaceWith = newStr[i];i++;//wdReplaceAll - 替换找到的所有项。

ASP导出为Word或Excel的最简单方法

ASP导出为Word或Excel的最简单方法

Asp代码‎EX‎C EL ‎<% ‎Re‎s pons‎e.Con‎t entT‎y pe =‎"appl‎i cati‎o n/vn‎d.ms-‎e xcel‎"R‎e spon‎s e.Ad‎d Head‎e r "C‎o nten‎t-Dis‎p osit‎i on",‎"att‎a chme‎n t; f‎i lena‎m e=表格‎.xls"‎%>‎‎WOR‎D‎<% ‎Resp‎o nse.‎C onte‎n tTyp‎e ="a‎p plic‎a tion‎/vnd.‎m s-wo‎r d" ‎Resp‎o nse.‎A ddHe‎a der ‎"Cont‎e nt-D‎i spos‎i tion‎", "a‎t tach‎m ent;‎file‎n ame=‎文档.do‎c" ‎%>‎导出为‎W ORD时‎,若文档中‎含有表格,‎需要打打印‎,则要在导‎出的页面中‎加入下面的‎样式。

‎C ss代码‎<s‎t yle ‎t ype=‎"text‎/css"‎>‎<!-- ‎ta‎b le{ ‎bo‎r der-‎c olla‎p se:c‎o llap‎s e;bo‎r der:‎n one;‎m so-b‎o rder‎-alt:‎s olid‎wind‎o wtex‎t .5p‎t; ‎mso-‎y fti-‎t bllo‎o k:48‎0;mso‎-padd‎i ng-a‎l t:0c‎m 5.4‎p t 0c‎m 5.4‎p t;ms‎o-bor‎d er-i‎n side‎h: ‎.5pt‎soli‎d win‎d owte‎x t;ms‎o-bor‎d er-i‎n side‎v:.5p‎t sol‎i d wi‎n dowt‎e xt;b‎o rder‎-left‎:soli‎dwin‎d owte‎x t 1.‎0pt;b‎o rder‎-top:‎s olid‎wind‎o wtex‎t 1.0‎p t; ‎} ‎td{‎b‎o rder‎-top:‎n one;‎b orde‎r-lef‎t: ‎none‎;bord‎e r-bo‎t tom:‎s olid‎wind‎o wtex‎t 1.0‎p t;bo‎r der-‎r ight‎:soli‎d win‎d owte‎x t 1.‎0pt; ‎ms‎o-bor‎d er-t‎o p-al‎t:sol‎i d wi‎n dowt‎e xt .‎5pt;m‎s o-bo‎r der-‎l eft-‎a lt:s‎o lid ‎w indo‎w text‎.5pt‎;‎m so-b‎o rder‎-alt:‎s olid‎wind‎o wtex‎t .5p‎t;pad‎d ing:‎0cm 5‎.4pt ‎0cm 5‎.4pt;‎}‎-‎-> ‎</st‎y le> ‎<s‎t yle ‎t ype=‎"text‎/css"‎><!-‎-tab‎l e{b‎o rder‎-coll‎a pse:‎c olla‎p se;b‎o rder‎:none‎;mso-‎b orde‎r-alt‎:soli‎d win‎d owte‎x t .5‎p t;m‎s o-yf‎t i-tb‎l look‎:480;‎m so-p‎a ddin‎g-alt‎:0cm ‎5.4pt‎0cm ‎5.4pt‎;mso-‎b orde‎r-ins‎i deh:‎.5pt‎soli‎d win‎d owte‎x t;ms‎o-bor‎d er-i‎n side‎v:.5p‎t sol‎i d wi‎n dowt‎e xt;b‎o rder‎-left‎:soli‎dwin‎d owte‎x t 1.‎0pt;b‎o rder‎-top:‎s olid‎wind‎o wtex‎t 1.0‎p t;}‎td{‎b orde‎r-top‎:none‎;bord‎e r-le‎f t:n‎o ne;b‎o rder‎-bott‎o m:so‎l id w‎i ndow‎t ext ‎1.0pt‎;bord‎e r-ri‎g ht:s‎o lid ‎w indo‎w text‎1.0p‎t;ms‎o-bor‎d er-t‎o p-al‎t:sol‎i d wi‎n dowt‎e xt .‎5pt;m‎s o-bo‎r der-‎l eft-‎a lt:s‎o lid ‎w indo‎w text‎.5pt‎; mso‎-bord‎e r-al‎t:sol‎i d wi‎n dowt‎e xt .‎5pt;p‎a ddin‎g:0cm‎5.4p‎t 0cm‎5.4p‎t;}‎--><‎/styl‎e>‎系统项目中‎的一个导出‎为EXCE‎L文件的实‎例代码如下‎:As‎p代码‎<!--‎#incl‎u de f‎i le="‎h bwlC‎o nfig‎.asp"‎--> ‎<%‎R espo‎n se.C‎o nten‎t Type‎="ap‎p lica‎t ion/‎v nd.m‎s-exc‎e l" ‎R‎e spon‎s e.Ad‎d Head‎e r "C‎o nten‎t-Dis‎p osit‎i on",‎"att‎a chme‎n t; f‎i lena‎m e=ch‎e ngji‎.xls"‎%> ‎<!DO‎C TYPE‎html‎PUBL‎I C "-‎//W3C‎//DTD‎XHTM‎L 1.0‎Tran‎s itio‎n al//‎E N""‎h ttp:‎//www‎.w3.o‎r g/TR‎/xhtm‎l1/DT‎D/xht‎m l1-t‎r ansi‎t iona‎l.dtd‎"> ‎<htm‎l xml‎n s="h‎t tp:/‎/www.‎w3.or‎g/199‎9/xht‎m l"> ‎<h‎e ad> ‎<m‎e ta h‎t tp-e‎q uiv=‎"Cont‎e nt-T‎y pe" ‎c onte‎n t="t‎e xt/h‎t ml; ‎c hars‎e t=ut‎f-8" ‎/> ‎<tit‎l e>成绩‎</tit‎l e> ‎<st‎y le t‎y pe="‎t ext/‎c ss">‎.‎t able‎W g {b‎o rder‎:1px ‎s olid‎#9bb‎d e6;}‎.‎t able‎W g tr‎{text‎-alig‎n:cen‎t er;}‎.‎t able‎W g td‎{ bor‎d er-b‎o ttom‎:1px ‎d otte‎d #9b‎b de6;‎bord‎e r-ri‎g ht:1‎p x do‎t ted ‎#9bbd‎e6;} ‎</‎s tyle‎>‎</hea‎d> ‎<bod‎y> ‎<%sq‎l=ses‎s ion(‎"chen‎g jisq‎l") ‎res‎p onse‎.Writ‎e hbw‎l.dbS‎e lect‎(sql,‎0,1,"‎",0,"‎",0,"‎t able‎W g")%‎>‎</bod‎y> ‎</ht‎m l> ‎<%s‎e t hb‎w l=no‎t hing‎%>‎‎。

ASP.NET----实现网页中查看offic文件,word,ppt等

ASP.NET----实现网页中查看offic文件,word,ppt等

----实现⽹页中查看offic⽂件,word,ppt等原理很简单,实现⼀个树,先获取⽂件存放⽂件夹地址,然后遍历每个⽂档,填⼊到树节点中去,看下截图效果:具体看下⾯代码:File.cs:public partial class Files : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if(!this.IsPostBack)this.InitTree();}private void InitTree(){//清除树节点this.trvFiles.Nodes.Clear();//实例化根节点TreeNode node = new TreeNode();node.Text = "简历⽂件";node.Value = "";//获取存放Word PPT⽂件的⽂件夹路径string dicPath = this.Server.MapPath("WordFiles");//实例化⽂件夹对象DirectoryInfo dic = new DirectoryInfo(dicPath);//循环获取Word⽂档⽂件foreach (FileInfo file in dic.GetFiles("*.doc")){//实例化⽂件节点TreeNode fileNode = new TreeNode();//赋值fileNode.Text = ;fileNode.Value = file.FullName;//添加⾄根节点中node.ChildNodes.Add(fileNode);continue;}//循环获取PPT⽂件foreach (FileInfo file in dic.GetFiles("*.ppt")){TreeNode fileNode = new TreeNode();fileNode.Text = ;fileNode.Value = file.FullName;node.ChildNodes.Add(fileNode);continue;}//展开⽂件夹节点node.Expand();this.trvFiles.Nodes.Add(node);}protected void trvFiles_SelectedNodeChanged(object sender, EventArgs e){//判断选中节点不是根节点if (!string.IsNullOrEmpty(this.trvFiles.SelectedNode.Value)){//拼装打开⽂件的JavaScript脚本string js = "window.frames[0].location.href='{0}';";js = string.Format(js, "WordFiles/" + this.trvFiles.SelectedNode.Text);//执⾏脚本即在DocShow.aspx页⾯打开相应节点this.WriteJS(js);}}protected void WriteJS(string msg){string script = string.Format("<script type='text/javascript' language='javascript'>{0}</script>", msg);this.ClientScript.RegisterStartupScript(this.GetType(), "alert", script);}protected void AlertMsg(string msg){string script = string.Format("<script type='text/javascript' language='javascript'>window.alert('{0}');</script>",msg);this.ClientScript.RegisterStartupScript(this.GetType(),"alert",script);}}页⾯布局:<body><form id="form1" runat="server"><div><table style="border: none; padding: none; margin: none; width: 100%; height: 100%;"><tr><td style="width:20%;height:100%;vertical-align:top;"><asp:TreeView ID="trvFiles" runat="server" ImageSet="XPFileExplorer" NodeIndent="15"OnSelectedNodeChanged="trvFiles_SelectedNodeChanged"><ParentNodeStyle Font-Bold="False"/><HoverNodeStyle Font-Underline="True" ForeColor="#6666AA"/><SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px"VerticalPadding="0px"/><NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px"NodeSpacing="0px" VerticalPadding="2px"/></asp:TreeView></td><td><iframe style="scroll:auto;width:100%;height:800px;border:none;" src="DocShow.aspx"></iframe></td></tr></table></div></form></body>⽹盘下载:。

asp.net按指定模板导出word,pdf

asp.net按指定模板导出word,pdf

按指定模板导出word,pdf///<summary>///导出word⽂件///</summary>///<param name="templateFile">模板路径</param>///<param name="fileNameWord">导出⽂件名称</param>///<param name="fileNamePdf">pdf⽂件名称</param>///<param name="bookmarks">模板内书签集合</param>///<param name="invoiceline">发票条⽬列表</param>public static void GenerateWord(string templateFile, string fileNameWord, string fileNamePdf, Dictionary<string, string> bookmarks, List<InvoiceLineView> invoiceline) {Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();File.Copy(templateFile, fileNameWord, true);Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();object Obj_FileName = fileNameWord;object Visible = false;object ReadOnly = false;object missing = System.Reflection.Missing.Value;doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing, ref Visible, ref missing, ref missing, ref missing, ref missing);doc.Activate();foreach (string bookmarkName in bookmarks.Keys){object BookMarkName = bookmarkName;//获得书签名Range range = doc.Bookmarks.get_Item(ref BookMarkName).Range;//表格插⼊位置range.Text = bookmarks[bookmarkName];}object IsSave = true;object FileName = fileNamePdf;object FileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;object LockComments = false;object AddToRecentFiles = true;object ReadOnlyRecommended = false;object EmbedTrueTypeFonts = false;object SaveNativePictureFormat = true;object SaveFormsData = false;object SaveAsAOCELetter = false;object Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingSimplifiedChineseGB18030;object InsertLineBreaks = false;object AllowSubstitutions = false;object LineEnding = Microsoft.Office.Interop.Word.WdLineEndingType.wdCRLF;object AddBiDiMarks = false;doc.SaveAs(ref FileName, ref FileFormat, ref LockComments,ref missing, ref AddToRecentFiles, ref missing,ref ReadOnlyRecommended, ref EmbedTrueTypeFonts,ref SaveNativePictureFormat, ref SaveFormsData,ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks,ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks);doc.Close(ref IsSave, ref missing, ref missing);}调⽤Dictionary<string, string> bookmarks = new Dictionary<string, string>();bookmarks.Add("ContractDueDateTime", invoice.InvoiceTime.AddDays(invoice.ContractDueDate).ToString("D"));bookmarks.Add("CustomContactEmail", invoice.CustomContactEmail);bookmarks.Add("CustomContactName", invoice.CustomContactName);bookmarks.Add("ContractDueDate", invoice.ContractDueDate.ToString());bookmarks.Add("CustomContactTel", invoice.CustomContactTel);bookmarks.Add("CustomAddress", invoice.CustomAddress);bookmarks.Add("InvoiceTime", invoice.InvoiceTime.ToString());bookmarks.Add("InvoiceID", invoice.InvoiceID);bookmarks.Add("CustomName", invoice.CustomName);bookmarks.Add("CustomName2", invoice.CustomName);bookmarks.Add("total", invoice.TotalPrice.ToString("C"));bookmarks.Add("total1", invoice.TotalPrice.ToString("C"));bookmarks.Add("totalTax", invoice.TotalTax.ToString("C"));bookmarks.Add("totalPrice", (invoice.TotalPrice + invoice.TotalTax).ToString("C"));bookmarks.Add("totalPrice1", (invoice.TotalPrice + invoice.TotalTax).ToString("C"));bookmarks.Add("totalPrice2", (invoice.TotalPrice + invoice.TotalTax).ToString("C"));bookmarks.Add("totalPrice3", (invoice.TotalPrice + invoice.TotalTax).ToString("C"));bookmarks.Add("totalPrice4", (invoice.TotalPrice + invoice.TotalTax).ToString("C"));Utility.GenerateWord(templateFile, fileNameWord, fileNamePdf, bookmarks, invoiceline);新建⼀个word,在需要替换的位置插⼊书签,使⽤以上⽅法即可将书签处替换为指定内容,并且另存为pdf。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

11.1 Web打印Web打印是一种常用的打印方式,其使用方法简单、方便、快捷,在浏览网页的同时就可以实现打印的功能。

实例291 调用IE自身的打印功能实现打印实例说明通过JavaScript调用IE自身的打印功能实现打印,这种方法比较简单,也是常用的打印方式。

使用该方法只须将要打印的页面设计好,再通过JavaScript的window对象的print( )方法调用IE的打印功能即可。

运行本实例,单击“打印”超级链接,会弹出打印对话框,如图11.1所示,然后进行相应的设置,并进行打印。

图11.1 调用IE自身的打印功能实现打印技术要点本实例主要通过调用window对象的打印方法print()来实现打印功能。

window对象的print()方法的语法格式如下:window.print();例如:<a href="#" onClick="window.print()">打印</a>实现过程(1)设计要打印的页面。

(2)调用window对象的打印方法实现打印功能,代码如下:<a href="#" onClick="window.print()">打印</a>举一反三根据本实例,读者可以:开发打印库存统计报表;打印校友录中的同学联系方式。

实例292 打印指定框架中的内容实例说明在实例292中已经介绍如何通过JavaScript调用IE自身的打印功能实现打印,但是该方法将打印页面中的全部内容,包括“打印”超级链接,有时这是不需要的,本实例将介绍如何通过打印指定框架中的内容实现页面部分内容打印。

运行本实例,如图11.2所示,单击“打印”超级链接,会弹出打印对话框,进行相应的设置后,单击“打印”按钮即可对图11.2中的表格内容进行打印。

图11.2 打印指定框架中的内容技术要点在实现打印指定框架中内容时,首先需要让要打印的框架获得焦点,然后再调用window对象的print()方法实现打印。

语法:parent.mainFrame.fcous();window.print();参数说明l mainFrame:表示框架的名称。

实现过程(1)设计content.htm页面,将要打印的内容放置在该页面中。

(2)设计index.htm页面,在该页面的适当位置添加浮动框架(应用<iframe>标记创建),并将该浮动框架的src属性指定为步骤(1)中创建的content.htm文件,代码如下:<iframe name="contentFrame" src="content.htm" frameborder="0" width="100%" height="100%"></iframe>(3)在index.htm页面中添加“打印”超级链接,打印指定浮动框架中的内容,代码如下:<a href="#" onClick="parent.contentFrame.focus();window.print();">打印</a>举一反三根据本实例,读者可以:开发打印库存盘点报表;实现在办公自动化系统中加入打印考勤明细表功能。

实例293 利用WebBrowser打印实例说明WebBrowser是IE内置的浏览器控件,无须用户下载。

它的优点是客户端独立完成打印目标文档的生成,减轻服务器负荷;缺点是源文档的分析操作复杂,并且要对源文档中要打印的内容进行约束。

运行本实例,单击“打印预览”超级链接,即可打开“打印预览”对话框,如图11.3所示,单击“打印”超级链接,即可打开打印对话框进行打印。

图11.3 利用WebBrowser打印技术要点本实例主要应用IE内置的WebBrowser控件实现,该控件的具体参数如下。

l document.all.WebBrowser.Execwb(7,1):表示打印预览。

l document.all.WebBrowser.Execwb(6,1):表示打印。

l document.all.WebBrowser.Execwb(6,6):表示直接打印。

l document.all.WebBrowser.Execwb(8,1):表示页面设置。

实现过程(1)建立HTML的Object标签,调用WebBrowser控件,代码如下:<object id="WebBrowser" classid="ClSID:8856F961-340A-11D0-A96B-00C04Fd705A2" width="0" height="0"></object>(2)建立相关的打印超级链接,并调用WebBrowser控件的相应参数实现打印预览、打印等功能。

代码如下:<a href="#" onClick="document.all.WebBrowser.Execwb(7,1)">打印预览</a> <a href="#"onClick="document.all.WebBrowser.Execwb(6,1)">打印</a> <a href="#" onClick="document.all.WebBrowser.Execwb(6,6)">直接打印</a> <a href="#" onClick="document.all.WebBrowser.Execwb(8,1)">页面设置</a>举一反三根据本实例,读者可以:实现在网站中打印各种报表功能;实现在网站中打印单据功能。

实例294 设置页眉页脚实例说明在系统默认的情况下,无论是利用IE自身的打印功能进行打印,还是利用IE自带的WebBrowser控件进行打印,在打印的文档顶部和底部会包括页眉和页脚,有时并不需要打印默认的页眉和页脚。

本实例将介绍如何清空页眉页脚和恢复页眉页脚。

运行本实例,单击“清空页眉页脚”超级链接,即可清空IE默认的页眉页脚,这时再单击“打印预览”超级链接,在打开的“打印预览”窗口中将不显示IE默认的页眉页脚,如图11.4所示,单击“恢复页眉页脚”超级链接即可恢复页眉页脚的显示。

图11.4 设置页眉页脚技术要点本实例主要通过WshShell 对象的相关方法实现。

WshShell对象是WSH(WSH是Windows Scripting Host的缩写,内嵌于Windows操作系统中的脚本语言工作环境)的内建对象,主要负责程序的本地运行、处理注册表、创建快捷方式、获取系统文件夹信息及处理环境变量等工作。

WshShell 对象的相关方法如表11.1所示。

表11.1 WshShell对象的相关方法方法说明CreateShortcut创建并返回WshShortcut对象ExpandEnvironmentStrings扩展PROCESS环境变量并返回结果字符串Popup显示包含指定消息的消息窗口RegDelete从注册表中删除指定的键或值RegRead从注册表中返回指定的键或值RegWrite在注册表中设置指定的键或值Run创建新的进程,该进程用指定的窗口样式执行指定的命令本实例中主要应用了RegWrite方法,下面将对该方法进行详细介绍。

RegWrite方法用于在注册表中设置指定的键或值,其语法格式如下:WshShell.RegWrite strName, anyV alue, [strType]参数说明l strName:用于指定注册表的键或值,若strName以一个反斜杠(在JavaScript中为\\) 结束,则该方法设置键,否则设置值。

strName 参数必须以根键名“HKEY_CURRENT_USER”、“HKEY_LOCAL_MACHINE”、“HKEY_CLASSES_ROOT”、“HKEY_USERS”或“HKEY_CURRENT_CONFIG”开头。

l AnyV alue:用于指定注册表的键或值的值。

当strType为REG_SZ或REG_EXPAND_SZ 时,RegWrite方法自动将anyV alue转换为字符串。

若strType为REG_DWORD,则anyV alue 被转换为整数。

若strType为REG_BINARY,则anyV alue必须是一个整数。

l StrType:用于指定注册表的键或值的数据类型。

RegWrite方法支持的数据类型为REG_SZ、REG_EXPAND_SZ、REG_DWORD和REG_BINARY。

其他的数据类型被作为strType传递,RegWrite 返回E_INV ALIDARG。

实现过程(1)编写自定义JavaScript函数PageSetup_del()和PageSetup_set(),用于实现清空页眉页脚和恢复页眉页脚的功能。

具体代码如下:<script language="JavaScript">var HKEY_RootPath="HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";function PageSetup_del(){ //清空页眉页脚try{var WSc=new ActiveXObject("WScript.Shell");HKEY_Key="header";WSc.RegWrite(HKEY_RootPath+HKEY_Key,"");HKEY_Key="footer";WSc.RegWrite(HKEY_RootPath+HKEY_Key,"");}catch(e){}}function PageSetup_set(){ //恢复页眉页脚try{var WSc=new ActiveXObject("WScript.Shell");HKEY_Key="header";WSc.RegWrite(HKEY_RootPath+HKEY_Key,"&w&b页码,&p/&P");HKEY_Key="footer";WSc.RegWrite(HKEY_RootPath+HKEY_Key,"&u&b&d");}catch(e){}}</script>(2)建立HTML的Object标签,调用WebBrowser控件,代码如下:<object id="WebBrowser" classid="ClSID:8856F961-340A-11D0-A96B-00C04Fd705A2" width="0" height="0"></object>(3)创建“清空页眉页脚”和“恢复页眉页脚”的超级链接,并调用自定义函数PageSetup_del()和PageSetup_set()实现相应功能。

相关文档
最新文档