Using RTF in VB.NET to create a document - asp.net

Thanks for viewing my post. I'm looking for ideas regarding creating a document with rtf. I started using word to create a word document automatically, but word automation does not work too well server side, and it is not recommended to do so by Microsoft. I know how to do basic text with rtf, but I'm wondering if I could create a template with bookmarks and fill in these bookmarks with data from a database. Any ideas would be appreciated. I'm not looking for handouts (ex- coding), just looking for ideas. Thank again for your time! Any info will be greatly appreciated! I'm using asp.net.
Josh

RTF stand for Rich Text Format. the toolbox contains a RichTextBox control which will read,edit, and write rtf documents. You can easily extend this to get the functionality you want. Here's an example
Here's an example of a rich text editing control for asp.net

I'm going to go at this in a new way. I'm going to create a html document with 'placeholders'. Then I will call on the document to save with the .doc extension. Testing has shown that Microsoft Word will open this document. Thanks again.
Josh
Public Function GetTemplate( _
ByVal strTemplateFile As String) As String
Dim strPath As String = ""
strPath = Server.MapPath("~/Templates") & "\" & strTemplateFile
Return My.Computer.FileSystem.ReadAllText(strPath)
End Function
and
Dim strTemplate As String = ""
Dim blnLB As Boolean = True
strTemplate = GetTemplate("Legislative_Bulletin.htm")
Response.AppendHeader("Content-Type", "application/msword")
Response.AppendHeader("Content-disposition", "attachment; filename=Legislative_Bulletin" & ".doc")
Response.Write(strTemplate)
Response.End()
this is just example coding. you will still need to insert the data into the placeholders of the html template. I hope this helps someone!
Josh

Related

ASP.NET Export - Response not ending?

I'm trying to export some text to a text file, and that part works fine. The trouble is that the text files get a bunch of HTML/.NET output at the bottom of them... In other words, it's like the response isn't ending and the page is trying to write the rest of the page. Here's the code:
Private Sub WriteData(ByRef Context As System.Web.HttpContext, Data As List(of String), fileName as String)
With Context.Response
.Clear()
.ClearHeaders()
.ClearContent()
.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
.ContentType = contentType
End With
For Each curValue in Data
Context.Response.Write(curValue)
Context.Response.Write(Environment.NewLine)
Next
Context.ApplicationInstance.CompleteRequest()
Context.Response.End()
End Sub
To call this, I just pass the HttpContext.Current and a list of data.
Does anybody know why this might happen? I'm not sure how to interpret it, and I've looked all over without much luck. My assumption was that the response wasn't actually ending with "Response.End()"...
Thanks,
Mike
My assumption is that you're using an .aspx to do this.
This would be a perfect scenario for a Generic Handler. Try using .ashx instead.
Here is a pretty simple tutorial if you need more info:
http://www.brainbell.com/tutorials/ASP/Generic_Handlers_%28ASHX_Files%29.html

Trouble Understanding Code to Export Excel Spreadsheet from HTML

I have been asked to make changes to an ASP.NET WebForms application written in VB (I normally use C#).
One task is to try and fix an Excel download. The client reported that he gets an error about the spreadsheet being corrupt when he attempts to open it in Excel.
The code that exports the Excel download appears in the Load event of a dedicated ASPX page. And looks something like this:
Dim mytable As New HtmlTable
mytable = [Populate HTML Table Here]
mytable = returnclass.displaytable
mytable.Border = 1
mytable.BorderColor = "#CCCCCC"
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Buffer = True
Response.Write("<html xmlns:x=""urn:schemas-microsoft-com:office:excel"">")
Response.Write("<head>")
Response.Write("<!--[if gte mso 9]><xml>")
Response.Write("<x:ExcelWorkbook>")
Response.Write("<x:ExcelWorksheets>")
Response.Write("<x:ExcelWorksheet>")
Response.Write("<x:Name>" & worksheetTitle & "</x:Name>")
Response.Write("<x:WorksheetOptions>")
Response.Write("<x:Print>")
Response.Write("<x:ValidPrinterInfo/>")
Response.Write("</x:Print>")
Response.Write("</x:WorksheetOptions>")
Response.Write("</x:ExcelWorksheet>")
Response.Write("</x:ExcelWorksheets>")
Response.Write("</x:ExcelWorkbook>")
Response.Write("</xml>")
Response.Write("<![endif]--> ")
Response.Write("</head>")
Response.Write("<body>")
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=hhexport.xls ")
HttpContext.Current.Response.Charset = ""
'ouput table to html so excel can interperet.
Me.EnableViewState = False
Dim stringWriter As New System.IO.StringWriter()
Dim htmlWriter As New System.Web.UI.HtmlTextWriter(stringWriter)
mytable.RenderControl(htmlWriter)
HttpContext.Current.Response.Write(stringWriter.ToString)
I really don't understand what this is trying to do.
Questions:
The code produces a regular ASP.NET HtmlTable and assigns it to mytable. On what planet can Excel open HTML?
I'm really kind of loss by the XML in general here, and by the <!--[if gte mso 9] comment. Can anyone help me understand what is going on here.
The result appears valid but I'm just not familiar with what the intent is here. Any tips appreciated.
EDIT
On further testing, the problem seems related to the extension given to the file (xls). The current version of Excel will go ahead and load the file if I indicate that. But all formatting is lost. Any suggestions on what type of file this would be?
EDIT
And it looks like the original author got the idea from here, although that page doesn't really describe what is happening.
UPDATE
Thanks for everyone's response. I will credit those replies according to how they addressed the questions above. However, for my purposes the code appears to have worked all along. It just appears that newer versions of Excel now warn the user that an XLS file that contains HTML is a file of a different type than suggested by the file extension. And it appears there is nothing that can be done about this except for exporting using CSV, OpenXML or some other approach. I found more details in this blog.
The code basically wraps an HTML table in some special XML tags that relate to Excel (defining a Workbook and Worksheets, etc). This is supposed to allow the output to be opened by either Excel or a browser.
To answer your questions:
The code produces a regular ASP.NET HtmlTable and assigns it to mytable. On what planet can Excel open HTML? Actually, that's a feature of Excel. You can use a special combination of XML and HTML tags to create files that are open-able on the web and in Excel. See this MSDN article: How to format an Excel workbook while streaming MIME content
I'm really kind of loss by the XML in general here, and by the <!--[if gte mso 9] comment. Can anyone help me understand what is going on here. That specific comment is checking for the availability of MS Excel (whether it's being opened by Excel or a browser), I believe. The XML is specific tags that have special meaning in MS Excel. There's a reference you can download here: Microsoft® Office HTML and XML Reference
I found this article on C# Corner to be pretty helpful in understanding this type of code: Creating a Dynamic Excel Using HTML.
As far as I know Excel has been able to read HTML for quite a while. This particular approach is pretty common, but it's definitely not best practice.
The important part of this logic is here:
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=hhexport.xls ")
HttpContext.Current.Response.Charset = ""
'ouput table to html so excel can interperet.
Me.EnableViewState = False
Dim stringWriter As New System.IO.StringWriter()
Dim htmlWriter As New System.Web.UI.HtmlTextWriter(stringWriter)
mytable.RenderControl(htmlWriter)
HttpContext.Current.Response.Write(stringWriter.ToString)
The Response.Write logic is just being used to control the workbook and worksheet that gets outputted. If that logic was not there, the file would open with three worksheets similar to a new Excel workbook.

How to add a hyperlink in a text file in ASP.NET using VB

I have tow pages, first one for displaying the data in the text file and the other one is to store the data. I want to save a site in the text file but when i display the data will be just text and I can't click it as a link. The code I post is when I write to a file in display page.
Try
Dim fs As String
fs = Server.MapPath("Footer.txt")
lblsplittext.Text = ""
Dim filestream As StreamReader
filestream = New IO.StreamReader(fs)
Dim readcontents As String = filestream.ReadToEnd()
Dim textdelimiter As String = "#"
Dim splitout = Split(readcontents, textdelimiter)
Dim i As Integer
For i = 0 To UBound(splitout)
lblsplittext.Text &= splitout(i) & "<br>"
Next
filestream.Close()
Catch ex As Exception
Dim str As String
str = ex.Message
End Try
If you have a different suggestion about how to read from a file or database (it doesnt matter from where for now) just keep in mine when i display them i just need to have hyperlinks among my text... Or can I write to html file instead of text file if so what is the difference i need to make to write to html. I really really need help here and i have done many searches but i found nothing.
Thanks in advance.
There are a number of ways you could do this. One would be to use a series of dynamically-added Label controls. Your Hyperlink control could simply be inserted between one Label control and the next.
Do you intend to retrieve information from your series of labels on postback? (It would be redundant to do that, since you already know what the information is, but just in case.) Using multiple controls would make that more complicated. You could try one or more Literal controls, created dynamically and added as child controls to a Panel control. Again, the Hyperlink control would be added at whatever time you need it.

Simple Question, how to I create a dynamic CSV - ASP.NET, VB

Howdy, Now I'm a complete newby to .Net and the likes of VB (I'm more of a Ruby/Rails, PHP kinda guy).
Anyway I currently have a sub that has a string builder that I'm wish to use as the content of a CSV which I will email later from a webpage. My stringbuilder is creating the content for the CSV but I don't know how to create the CSV dynamically (I don't want the CSV on disk).
Private Shared Sub BuildClientTrustBalanceCSV(ByVal sb As StringBuilder, ByVal clientsWithTrustBalance As List(Of NonPaymentHistory))
If clientsWithTrustBalance Is Nothing OrElse clientsWithTrustBalance.Count = 0 Then
Exit Sub
End If
' need to somewhere create the CSV then inject the StringBuilder into it?
With sb
' create the CSV
For Each zeroBalanceClient As NonPaymentHistory In clientsWithTrustBalance
.AppendFormatLine("{0},", zeroBalanceClient.Number)
Next zeroBalanceClient
End With
End Sub
Any ideas? I know I should be able to sort this but .NET just isn't my thing?
Here is a link that might be helpful, but I agree with Oded that the question is misleading.
How do I best generate a CSV (comma-delimited text file) for download with ASP.NET?

FileUpload control event

I want to know how to raise an event for fileupload control....
In my project, as soon as I select a file(Image) it should show FILENAME,EXTENSION & SIZE in the labels given below.
Pls reply me....
Thanks in advance.
Until HTML5 becomes mainstream, it is completely impossible to do this without uploading the entire file to the server. (Except maybe with Flash)
Unfortunately this is not possible you need first to upload the file and then get it's information and add them to labels, otherwise you need to use third party plug-in to able you to do that such as flash or java applets.
You can use this code to get file information as soon as you select the file.
int filesize = FileUpload1.PostedFile.ContentLength;
string fileextension = FileUpload1.PostedFile.ContentType
string filename = Path.GetFileName(FileUpload1.FileName);

Resources