我的应用程序中有一个“导出到单词”功能。它完美地运作。我使用gridview的内容导出到word文件。
现在我想在导出的word文件中添加页眉/页脚,该文件由以下代码生成:
Dim fileName As String = "Test_" & Format(DateTime.Now, "MMddyyyyhhmmss") & ".doc"
Dim sw As New StringWriter()
Dim w As New HtmlTextWriter(sw)
gvContent.RenderControl(w)
Dim content As String = sw.GetStringBuilder().ToString()
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=" & fileName)
Response.Charset = ""
Response.ContentType = "application/vnd.ms-word"
Response.Write(finalContent)
Response.Flush()
Response.End()
标题&页脚应该显示在word文件的所有页面中,就像使用Word的页眉/页脚功能一样。
有可能吗?有没有人对此有所了解?
答案 0 :(得分:2)
您正在做的是实际创建HTML文件并为其提供Word知道要打开的扩展名。您没有创建真正的.DOC文件,但Word将识别HTML并显示它。
我怀疑它所寻找的HTML风格与它保存的风格相同。所以我在Word 2013中创建了一个新文档,添加了页眉和页脚,并将其保存为HTML文件。检查HTML文件后,Word似乎将其删除。所以我怀疑是否有一种在HTML文件中指定页眉和页脚的方法。
您可以做的是切换到生成真正的MS Word文件。这些将在各种Word客户端和Word等效版本(例如Mac版本,移动版本和Libre Office)上提供更好的支持。
Micrsoft提供了一个用于生成.DOCX文件的库,名为Open XML SDK。但是,我发现有点难以使用。
我个人曾多次使用DocX。以下是使用该库完成此操作的方法(代码取自this blog post):
C#
// Create a new document.
using (DocX document = DocX.Create(@"Test.docx"))
{
// Add Header and Footer support to this document.
document.AddHeaders();
document.AddFooters();
// Get the default Header for this document.
Header header_default = document.Headers.odd;
// Get the default Footer for this document.
Footer footer_default = document.Footers.odd;
// Insert a Paragraph into the default Header.
Paragraph p1 = header_default.InsertParagraph();
p1.Append("Hello Header.").Bold();
// Insert a Paragraph into the document.
Paragraph p2 = document.InsertParagraph();
p2.AppendLine("Hello Document.").Bold();
// Insert a Paragraph into the default Footer.
Paragraph p3 = footer_default.InsertParagraph();
p3.Append("Hello Footer.").Bold();
// Save all changes to this document.
document.Save();
}// Release this document from memory.
VB.NET(由Telerik翻译,因为我不懂VB.NET)
' Create a new document.
Using document As DocX = DocX.Create("Test.docx")
' Add Header and Footer support to this document.
document.AddHeaders()
document.AddFooters()
' Get the default Header for this document.
Dim header_default As Header = document.Headers.odd
' Get the default Footer for this document.
Dim footer_default As Footer = document.Footers.odd
' Insert a Paragraph into the default Header.
Dim p1 As Paragraph = header_default.InsertParagraph()
p1.Append("Hello Header.").Bold()
' Insert a Paragraph into the document.
Dim p2 As Paragraph = document.InsertParagraph()
p2.AppendLine("Hello Document.").Bold()
' Insert a Paragraph into the default Footer.
Dim p3 As Paragraph = footer_default.InsertParagraph()
p3.Append("Hello Footer.").Bold()
' Save all changes to this document.
document.Save()
End Using
' Release this document from memory.
请注意,上述代码取自2010年撰写的博客文章。图书馆可能会在六年内发生变化。