Grdview to excel and save so dialog box does not show - vb.net

i have the following code. which creates and saves an excel file with the content in grdview4 which is great. however at the end of the application it displays a disalog box which i do not want. is there anyways to get it do the dialog box does not show?
Response.ContentEncoding = System.Text.Encoding.Unicode
Response.ContentType = "application/vnd.ms-excel"
' Response.AddHeader("content-disposition", "attachment;filename=""C:\EchoBACs\RejectedBACSBACs\rejectedBacs" & NewDate & ".xls")
' Response.TransmitFile("C:\rejectedBacs" & NewDate & ".xls")
Response.Charset = ""
Me.EnableViewState = False
Dim oStringWriter As New System.IO.StringWriter
Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)
GridView4.HeaderRow.Style.Add("background-color", "#FFFFFF")
GridView4.RenderControl(oHtmlTextWriter)
Dim helpme As String = oStringWriter.ToString()
' Response.Write(oStringWriter.ToString())
' HttpContext.Current.Response.End()
File.WriteAllText("C:\EchoBACs\RejectedBACS\rejectedBacs" & NewDate & ".xls", helpme)
oHtmlTextWriter.Close()

Do not use response in that case, this will ask the Save as dialog box. If you want to save the file to your disk without any prompt do something like this. I am giving you in C#
System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
grid.HeaderStyle.Font.Bold = true;
grid.DataSource = datatable;
grid.DataMember = datatable.TableName;
grid.DataBind();
using(StreamWriter sw = new StreamWriter ("d:\\temp\test.xls"))
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
grid.RenderControl(hw);
}
}

Related

Show a popup after exporting in Excel in vb.net

Hi I've a procedure in my web site for exporting a datatable in xlsx with closedxml library and I want show a popup after finishing export but the popup not showed. Can anyone tell me how to show the popup ? This is my code
Protected Sub ExportExcel(dt, strTable)
Using wb As New XLWorkbook()
Dim ws = wb.Worksheets.Add(dt, "foglio1")
ws.Columns("I").Style.NumberFormat.Format = "#,##0.00"
Response.Clear()
Response.Buffer = True
Response.Charset = "UTF-8"
Response.ContentEncoding = System.Text.Encoding.Unicode
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment;filename=" & strTable & ".xlsx" )
try
Using MyMemoryStream As New MemoryStream()
wb.SaveAs(MyMemoryStream)
MyMemoryStream.WriteTo(Response.OutputStream)
Response.Flush()
Response.Close()
End Using
catch
finally
Dim scriptString as String = "<script language=JavaScript>"
scriptString += "alert('Export completed !" & strUser & "!');"
scriptString += "window.location.href='http://localhost/default.aspx';<"
scriptString += "/"
scriptString += "script>"
If(Not ClientScript.IsClientScriptBlockRegistered(Me.GetType(), "clientScript"))
ClientScript.RegisterClientScriptBlock(Me.GetType(), "clientScript",scriptString)
end If
end try
End Using
End Sub

UWP epPlus - choose directory to save

I am making an application in vb using UWP and epPlus along with it to save the current database to an excel file. I would create a pop up dialog box that will allow the client to select the directory they want to save the excel file to. There isn't a "Savefiledialog" in UWP... Ideas?
UPDATE
I tried to use FileSavePicker: if I save it in the principal directory (C:\, Desktop, Documents ...) epPlus doesn't work, but if I save it in another directory (D:\, USB...) it workes... How can I save it in the principal directory?
I post my code here:
Private Async Sub ButtonXls_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
OutputTextBlock.Text = ""
Dim savePicker As FileSavePicker = New FileSavePicker()
savePicker.SuggestedStartLocation = PickerLocationId.Desktop
savePicker.FileTypeChoices.Add("Microsoft Excel", New List(Of String)() From {
".xlsx"
})
savePicker.SuggestedFileName = "Riepilogo_Test"
Dim file As StorageFile = Await savePicker.PickSaveFileAsync()
If file IsNot Nothing Then
CachedFileManager.DeferUpdates(file)
Dim ExcelPkg As ExcelPackage = New ExcelPackage()
Dim wsSheet1 As ExcelWorksheet = ExcelPkg.Workbook.Worksheets.Add("Sheet1")
Using Rng As ExcelRange = wsSheet1.Cells(2, 2, 2, 2)
Rng.Value = "Text file on Excel here"
Rng.Style.Font.Size = 16
Rng.Style.Font.Bold = True
Rng.Style.Font.Italic = True
End Using
wsSheet1.Protection.IsProtected = False
wsSheet1.Protection.AllowSelectLockedCells = False
Dim filePath As FileInfo = New FileInfo(file.Path)
ExcelPkg.SaveAs(filePath)
Dim status As FileUpdateStatus = Await CachedFileManager.CompleteUpdatesAsync(file)
If status = FileUpdateStatus.Complete Then
OutputTextBlock.Text = "File " & file.Name & " was saved."
ElseIf status = FileUpdateStatus.CompleteAndRenamed Then
OutputTextBlock.Text = "File " & file.Name & " was renamed and saved."
Else
OutputTextBlock.Text = "File " & file.Name & " couldn't be saved."
End If
Else
OutputTextBlock.Text = "Operation cancelled."
End If
End Sub

VB.net Crystal report export to html and send as html mail body using outlook

I am trying to send contents of a crystal report as email body using outlook application.
Here is my code in VB.net
Imports outlook = Microsoft.Office.Interop.Outlook
Dim a As String = something.ConnectionString
Dim cryRpt As ReportDocument
Dim username As String = a.Split("=")(3).Split(";")(0) 'get username
Dim password As String = a.Split("=")(4).Split(";")(0) 'get password
cryRpt = New ReportDocument()
Dim Path As String = Application.StartupPath
Dim svPath As String = Application.StartupPath & "\PDF"
If Not Directory.Exists(svPath) Then
Directory.CreateDirectory(svPath)
End If
cryRpt.Load(Path & "\Reports\dr.rpt")
CrystalReportViewer1.ReportSource = cryRpt
cryRpt.SetDatabaseLogon(username, password)
CrystalReportViewer1.Refresh()
Dim myExportOptions As ExportOptions
myExportOptions = cryRpt.ExportOptions
myExportOptions.ExportDestinationType = ExportDestinationType.DiskFile
myExportOptions.ExportFormatType = ExportFormatType.HTML40 'i tried HTML32 also
Dim html40FormatOptions As HTMLFormatOptions = New HTMLFormatOptions()
html40FormatOptions.HTMLBaseFolderName = svPath
html40FormatOptions.HTMLFileName = "dr.htm"
html40FormatOptions.HTMLEnableSeparatedPages = False
html40FormatOptions.HTMLHasPageNavigator = False
html40FormatOptions.UsePageRange = False
myExportOptions.FormatOptions = html40FormatOptions
cryRpt.Export()
Try
Dim oApp As outlook.Application
oApp = New outlook.Application
Dim oMsg As outlook.MailItem
oMsg = oApp.CreateItem(outlook.OlItemType.olMailItem)
oMsg.Subject = txtSubject.Text
oMsg.BodyFormat = outlook.OlBodyFormat.olFormatHTML
oMsg.HTMLBody = ""
oMsg.HTMLBody = getFileAsString(svPath & "\PoPrt\QuotPrt.html")
oMsg.To = txtEmailId.Text
Dim ccArray As New List(Of String)({txtCC1.Text, txtCC2.Text, txtCC3.Text})
Dim cclis As String = String.Join(",", ccArray.Where(Function(ss) Not String.IsNullOrEmpty(ss)))
oMsg.CC = cclis
oMsg.Display(True)
Catch ex As Exception
MsgBox("Something went wrong", vbExclamation)
End Try
SvFormPanel3.Visible = False
the function
Private Function getFileAsString(ByVal file As String) As String
Dim reader As System.IO.FileStream
Try
reader = New System.IO.FileStream(file, IO.FileMode.Open)
Catch e As Exception
MsgBox("Something went wrong. " + e.Message, vbInformation)
End Try
Dim resultString As String = ""
Dim b(1024) As Byte
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Do While reader.Read(b, 0, b.Length) > 0
resultString = resultString & temp.GetString(b)
Array.Clear(b, 0, b.Length)
Loop
reader.Close()
Return resultString
End Function
The report will get exported to the specified location as html. And when we manually open that html file it displays perfectly with border lines and all.
But when its getting added as html body of outlook application, the formatting will be gone, and looks scattered.
can anyone help
Did you try this?
Open outlook, go to, File>Options>Mail
go to section MessageFormat and untick "Reduce message size by removing format..."
I have solved the issue by exporting it into PDF and then convert to Image and embed in email body.

How to search for files and attach them to a Email

I have an CheckedListbox (imported from mysql Database) that lists all my folders where my files are saved. And what I need to do is for every checked item in the CheckListbox, to search the folder and then attach the file from that folder to a Mail.
What I have done is to create an Email and to send it with only one attachment.
Just with the: "e_mail. Attachments. Add". The Mail will be generated and that found file will be attached and send.
But when I do that in a FOR EACH LOOP then no file will be selected and added to my Mail. The Mail will be generated and send without any errors, but there are no attached files.
Private Sub SendMail()
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("MAIL", "PASS")
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.DeliveryMethod = SmtpDeliveryMethod.Network
Smtp_Server.Host = "HOST"
If MonthTextBox.Text = "" Or MonthTextBox.ForeColor = Color.Silver Then
MsgBox("Input month please", Title:="MO Text Box")
Else
Dim MOTextValue As String = MonthTextBox.Text
Dim nowYear As Integer = Date.Now.Year
For Each itemchecked As DataRowView In CheckedListBoxWO.CheckedItems
Dim File_path As String = "C:\Test\" & itemchecked.Item(1) & "\" & nowYear & "\" & MOTextValue & "\"
Dim File_Name As String = Dir("C:\Test\" & itemchecked.Item(1) & "\" & nowYear & "\" & MOTextValue & "\File " & MOTextValue & "*.xlsx")
Dim attachmentFile As Net.Mail.Attachment = New Net.Mail.Attachment(File_path & File_Name)
e_mail.Attachments.Add(attachmentFile)
Next
Dim sb As New System.Text.StringBuilder
sb.AppendLine("Hello,<br />")
sb.AppendLine("<br />")
sb.AppendLine("Test Attachment,<br />")
sb.AppendLine("<br />")
sb.AppendLine("------------------------------------------<br />")
e_mail.From = New MailAddress("MY MAIL")
e_mail.To.Add("EMAIL")
e_mail.Subject = ("TESTFILE - " & MOTextValue & "")
e_mail.SubjectEncoding = System.Text.Encoding.UTF8
e_mail.IsBodyHtml = True
e_mail.Priority = MailPriority.Normal
e_mail.Body = sb.ToString()
e_mail.BodyEncoding = System.Text.Encoding.UTF8
Smtp_Server.Send(e_mail)
End If
MsgBox("Mails was sent", Title:="Mail")
End Sub
Like I told with this code the Mail will be created and send, but there is no Attachment file in it.
If I do it without the "FOR EACH"... loop, then one File will be added without a problem. But I need to add more files, actually for every checked Item in the CheckedListBox my program should search that folder and if there is a file than attach it in the Mail, and look in the other folder and so on...
Your adding attachments then newing up your e_mail object again, this will wipe your existing data, try removing the indicated line below:
sb.AppendLine("<br />")
sb.AppendLine("------------------------------------------<br />")
e_mail = New MailMessage() <--- remove this line
e_mail.From = New MailAddress("MY MAIL")
e_mail.To.Add("EMAIL")
The code is actually working, my problem was that the reference to this CheckListBox was incorrect, I have multiple CheckListBoxes, and that one in the Code was not the one I was actually using... But looking it from the bright side, THE CODE IS WORKING :)

How to change the name of the output text file automatically with textbox data in VB .Net

This is my code:
Dim objWriter1 As System.IO.StreamWriter, objWriter2 As System.IO.StreamWriter
objWriter1 = New System.IO.StreamWriter("D:\first.txt", True)
objWriter2 = New System.IO.StreamWriter("D:\second.txt", True)
What I really want is to change the name of the text file to be saved as one of the Textbox data (Textbox1.Text) automatically
Can I do that ???
Well I got figured it out myself
I used the following code
Dim objWriter1 As System.IO.StreamWriter, objWriter2 As System.IO.StreamWriter
objWriter1 = New System.IO.StreamWriter("D:\" + Textbox1.Text + "first.txt", True)
objWriter2 = New System.IO.StreamWriter("D:\" + Textbox1.Text + "second.txt", True)
Dim objWriter1 As System.IO.StreamWriter, objWriter2 As System.IO.StreamWriter
'Whatever the value is in textbox1, will be displayed as the name of the file
objWriter1 = New System.IO.StreamWriter("D:\" & textbox1.text & ".txt", True)
'Whatever the value is in textbox2, will be displayed as the name of the file
objWriter2 = New System.IO.StreamWriter("D:\" & textbox2.text & ".txt", True)