vb.net Word Document Replace Strings Images - asp.net

I am trying to create mail merge process with word document (images, text, html). I am finding help online for a desktop application, but trying to do it from a web aspx page.
here is code I tried
Dim wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True)
Using (wordDoc)
Dim docText As String = Nothing
Dim sr As StreamReader = New StreamReader(wordDoc.MainDocumentPart.GetStream)
Using (sr)
docText = sr.ReadToEnd
End Using
Dim regexText As Regex = New Regex("Hello world!")
docText = regexText.Replace(docText, "Hi Everyone!")
Dim sw As StreamWriter = New StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))
Using (sw)
sw.Write(docText)
End Using
End Using
but can not even run. I get an error in visual studio 2015.
Severity Code Description Project File Line Suppression State
Error BC30002 Type 'WordprocessingDocument' is not defined.
Any ideas?
thanks

Related

Zipping an ExcelPackage in vb.net

I have created an excel document in code and I'm trying to zip the file using ZipArchive. I was attempting to do this by using BinaryReader/Writers but the the stream that I tried to make doesn't seem to contain anything. Any ideas what I'm doing wrong?
Using zip As ZipArchive = New ZipArchive(MemoryStream, ZipArchiveMode.Create, True)
Dim excelFile As ZipArchiveEntry = zip.CreateEntry("QueryExportTest.xlsx")
Using writer As BinaryWriter = New BinaryWriter(excelFile.Open())
Dim excelReader As BinaryReader = New BinaryReader(excel.Stream())
While excelReader.PeekChar() <> -1
writer.Write(excelReader.ReadBoolean)
End While
End Using
End Using
excel was defined earlier with Dim excel As New ExcelPackage()

Print SSRS Report from Code (asp.net)

I have found good information on how to automatically download a file to the client advertised as a solution of how to print using code
(https://forums.asp.net/t/1233841.aspx?How+do+I+print+from+Reporting+Services+AUTOMATICALLY+in+VB+Net+web+app+)
but what I need to do is have the code print the document without the user interacting.
From what I have found it appears this can not be done as one might casually think. ReportViewer for example does not have a 'print' method.
The only two solutions appears to be to use ProcessStart (which then means saving the file to the file system before printing which I dont want to do)
or maybe (will be researching this today) create a subscription using code and then delete it later.
You are not able to print a report directly from your asp.net page. The reason for this is security. If it allowed you to send a file through the network and onto the clients computer, and then search the computer for a printer, this could cause major security issues. The report viewer does have a print icon, but this disappears when you deploy the project and run the page remotely. I have faced the same issue in the past and found it best to just export the report to say PDF and allow the user to Download it. I have used the below code to accomplish this task in the past:
Private Sub CreatePDFMatrix(fileName As String)
' ReportViewer1.LocalReport.DataSources.Clear()
Dim adapter As New ReportDataSetTableAdapters.vwPrintTagsTableAdapter
Dim table As New ReportDataSet.vwPrintTagsDataTable
Dim month = MonthName(Date.Today.Month)
Dim year = Date.Today.Year
Dim p(1) As ReportParameter
Dim warnings() As Warning
Dim streamIds As String()
Dim mimeType As String = String.Empty
Dim encoding As String = String.Empty
Dim extension As String = String.Empty
Dim adpt2 As New ReportDataSetTableAdapters.vwPrintTagsTableAdapter
adapter.FillForMainReport(table, DropDownList1.SelectedValue, g_Company, g_Division)
Me.ReportViewer1.LocalReport.DataSources.Add(New ReportDataSource("DataSet1", CType(table, DataTable))) 'Add(New ReportDataSource("ReportingData", CType(table, DataTable)))
Me.ReportViewer1.DataBind()
Dim viewer = ReportViewer1
viewer.ProcessingMode = ProcessingMode.Local
viewer.LocalReport.ReportPath = "Report1.rdlc"
p(0) = New ReportParameter("MonthYear", month & "-" & year)
Dim check = DropDownList1.SelectedValue
ReportViewer1.LocalReport.SetParameters(p(0))
p(1) = New ReportParameter("Location", DropDownList1.SelectedValue)
ReportViewer1.LocalReport.SetParameters(p(1))
Try
Dim bytes As Byte() = viewer.LocalReport.Render("PDF", Nothing, mimeType, encoding, ".pdf", streamIds, warnings)
Response.Buffer = True
Response.Clear()
Response.ContentType = mimeType
Response.AddHeader("content-disposition", Convert.ToString((Convert.ToString("attachment; filename=") & fileName) + ".") & extension)
Response.BinaryWrite(bytes)
' create the file
Response.Flush()
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Sub

How to Edit Excel with EPPLUS and send it as attachment

i have the following code, which it is working, it opens a file stream from an embedded Xlsx saves it on a memorystream then pass the value to the attachment and send it with no problem.
Private Sub SendFile2()
Dim path As String = Server.MapPath("~/App_Data/RQM.xlsx")
Using fileST As FileStream = IO.File.OpenRead(path)
Dim memStream As New MemoryStream()
memStream.SetLength(fileST.Length)
fileST.Read(memStream.GetBuffer(), 0, CInt(fileST.Length))
'' Code for MailMessage and SMTP goes here
MailMsg.Attachments.Add(New Attachment(memStream, "myFile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
End Using
End Using
End Sub
Now im trying to do some edition (adding some values to that file, but still working in a memorystream) but i am having some problems
i've added
Using pck As ExcelPackage = New ExcelPackage(memStream)
Dim xlswb As ExcelWorkbook = pck.Workbook
Dim xlsws As ExcelWorksheet = xlswb.Worksheets.First
xlsws.Cells(20, 4).Value = "HELLO WORLD"
pck.SaveAs(memStream)
End Using
Which when i put breakpoints i see pck getting the value of MemStream with a lenght of 83084 (the value of the original file) 81kb xlsx, when i add the value to the cell the lenght of memStream is 162143 so it seems it does some modifications, however when i send again the memstream trough
MailMsg.Attachments.Add(New Attachment(memStream, "myFile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
i receive a file of 165b, and i'm not sure what i am doing wrong.
Any help would be apreciated
Edit:
Well i wasn't able to save it with the same memStream so instead i did this.
memStream2 = New MemoryStream(pck.GetAsByteArray())
MailMsg.Attachments.Add(New Attachment(memStream2, "myFile2.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
And that worked as a charm. Hope is useful to anyone.

asp.net openxml open docx, change content and stream to user

My code is below. I'm trying to open a Word document with Open XML and change certain text. The document must then be send to the client where they can save it on their PC or Open it. It send a document to the client but it is blank. When I save my InMemory document it says the file cannot be open it must contain at least one root element. I'm using Visual STudio 2010 Express. Please help me. What is wrong with my code?
Dim fileName As String = "directory on server\doc.docx"
Dim myDocument As WordprocessingDocument = WordprocessingDocument.Open(fileName, True)
Dim docText As String = Nothing
Dim sr As StreamReader = New StreamReader(myDocument.MainDocumentPart.GetStream)
docText = sr.ReadToEnd
sr.Close()
Dim regexText As Regex = New Regex("XXXCourtXXX")
docText = regexText.Replace(docText, "JOHANNESBURG")
Dim ms As New MemoryStream()
Dim sw As StreamWriter = New StreamWriter(ms)
sw.Write(docText)
myDocument.MainDocumentPart.FeedData(ms)
Dim mem = New MemoryStream()
myDocument.MainDocumentPart.GetStream().CopyTo(Response.OutputStream)
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Response.AppendHeader("Content-Disposition", "attachment;filename=Notice.docx")
mem.Position = 0
mem.CopyTo(Response.OutputStream)
Response.Flush()
Response.End()
You're dimming a new memory stream mem, writing nothing to it and then copying it to the output stream. Remove all lines referencing your mem variable.

How to fill a word document using Visual Basic / Visual C# in ASP.NET

I'm looking for options to fill a Word Document from either Visual Basic, or Visual C#. I'm currently using merge fields, and the code below to fill specific fields in a Word Document, but now I've run into a situation where I need tabular data pushed to MS Word. Is there anyway to take data from a grid view (number of rows is dynamic), and import it into a Word Document Table using a merge field or something of that sort? I have to maintain the format of my template doc, and would like to be able to control the layout of the page ..
Dim templateDoc As String = Server.MapPath("\Userfiles\docs\" & location)
Dim mergePath As String = Server.MapPath("\App_Data\Temp\")
Dim mergeFileName As String = location.Replace("/", "_") & ".docx"
Dim mergeDoc As String = mergePath & "\" & mergeFileName
File.Copy(templateDoc, mergeDoc, True)
Using pkg As Package = Package.Open(mergeDoc, FileMode.Open, FileAccess.ReadWrite)
Dim uri As Uri = New Uri("/word/document.xml", UriKind.Relative)
Dim part As PackagePart = pkg.GetPart(uri)
Dim xmlMainXMLDoc As XmlDocument = New XmlDocument()
xmlMainXMLDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read))
Dim innerXml As String = xmlMainXMLDoc.InnerXml _
.Replace("«Corporate Legal Name»", businessName) _
.Replace("«Address 1»", mailingAddress1) _
.Replace("«Address 2»", mailingAddress2) _
.Replace("«City»", city)
xmlMainXMLDoc.InnerXml = innerXml
Using partWriter As New StreamWriter(part.GetStream(FileMode.Open, FileAccess.Write))
xmlMainXMLDoc.Save(partWriter)
End Using
pkg.Close()
End Using
You can write out in HTML and save it with a .doc extension and Word will handle it gracefully.
Just like my answer for your question regarding Excel, Office writer will work for you here too!

Resources