Export Gridview connected to MYSQL data to excel - mysql

I have a simple form created in Visual Studio (VB) which has a data gridview connected to a table in MySQL (hosted in a remote server).
I have the below code to export the grid view to Excel but it takes a really long time to export (around 15 minutes).
The table in MySQL is really small (1000 rows and 60 columns).
Is there a better way to export the complete MySQL table to excel?
PLEASE HELP
CODE:
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To DataGridView1.Rows.Count - 1
For j = 0 To DataGridView1.Columns.Count - 1
For k As Integer = 1 To DataGridView1.Columns.Count
On Error Resume Next
xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
Next
Next
Next
xlWorkSheet.SaveAs("C:\Users\USERNAME\Desktop\vbexcel.xlsx")
xlWorkBook.Close()

Is there two ways to do this :
using rdlc reports.
using gridview exporting.
first way you need to created rdlc report, then retrieving data into datatable, then call this code:
Dim MyDataSource As ReportDataSource = New ReportDataSource("ReportDataSet", MyDataTable)
reportviewer1.LocalReport.ReportPath = Server.MapPath("MyrdlcReportPath")
rvSmartCardsIssues.LocalReport.EnableExternalImages = True
rvSmartCardsIssues.LocalReport.DataSources.Clear()
rvSmartCardsIssues.LocalReport.DataSources.Add(MyDataSource )
rvSmartCardsIssues.LocalReport.Refresh()
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim bytes As Byte()
bytes = rvSmartCardsIssues.LocalReport.Render("Excel", Nothing, mimeType, encoding, extension, streamids, warnings)
HttpContext.Current.Response.Buffer = True
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ContentType = mimeType
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ExportedFileName.xls")
HttpContext.Current.Response.BinaryWrite(bytes)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
second way that based on this function :
Public Shared Sub ExportGridViewToExcelGridView(ByVal Filename As String, ByRef gvr As GridView, ByRef currentPage As Page)
Dim HtmlForm As System.Web.UI.HtmlControls.HtmlForm = New System.Web.UI.HtmlControls.HtmlForm()
currentPage.Controls.Add(HtmlForm)
HtmlForm.Controls.Add(gvr)
currentPage.Response.Clear()
currentPage.Response.Buffer = True
currentPage.Response.AddHeader("Content-Disposition", "attachment; filename=" & Filename)
currentPage.Response.ContentType = "application/vnd.ms-excel"
currentPage.Response.ContentEncoding = System.Text.Encoding.UTF8
currentPage.Response.Charset = ""
currentPage.EnableViewState = False
Using strwriter As New StringWriter
Dim htmlwrt As HtmlTextWriter = New HtmlTextWriter(strwriter)
HtmlForm.RenderControl(htmlwrt)
htmlwrt.Flush()
currentPage.Response.Write(strwriter.ToString)
currentPage.Response.End()
End Using
End Sub
make sure that when you use second way to set the gridview paging property to false.

Related

Slicing a string to read a html document in VB

I was hoping someone could help me figure out why this script will not return the link names. I am trying to return a sub-string from 'http://textfiles.com/directory.html' which just writes the link names to the console, but I am struggling. The main problem - as far as I can see - is in the 'do until' loop. The working code outputs the html text to the console more for my sake than anything else (it does this successfully), but this feature may also help you guys understand the total picture I am facing. Maybe after seeing the code/ understanding my goal you guys can see where I am going wrong AND/OR suggest a better method for achieving my goal. Thanks a ton!
Imports System.IO
Imports System.Text
Module Module1
Sub Main()
Dim line As String = ""
Dim lowBound As String = "<a href="""
Dim highBound As String = """>"
Console.WriteLine("Grab link names from textfiles.com")
Console.WriteLine("")
Dim siteName As String = "http://textfiles.com/directory.html"
Dim tmpString As StringBuilder = New StringBuilder
My.Computer.Network.DownloadFile(siteName, "C:\~\VisualStudio\BeginnerPractice\TextFileDotCom_GrabLinkNames\TextFileDotCom_GrabLinkNames\bin\debug\directory.html", False, 500)
Dim myReader As StreamReader = New StreamReader("C:\~\VisualStudio\BeginnerPractice\TextFileDotCom_GrabLinkNames\TextFileDotCom_GrabLinkNames\bin\debug\directory.html")
While Not IsNothing(line)
line = myReader.ReadLine()
If Not IsNothing(line) Then
tmpString.Append(line)
End If
End While
Dim pageText As String = tmpString.ToString
Console.WriteLine(pageText)
Dim intCounter As Integer = 1
Do Until intCounter >= Len(pageText)
Dim checkSub As String = Mid(pageText, intCounter + 1, (Len(pageText) - intCounter))
Dim positLow As Integer = InStr(checkSub, lowBound)
Dim positHigh As Integer = InStr(checkSub, highBound)
If (positLow > 0 And positHigh > 0) And positLow < positHigh Then
Dim indexLow As Integer = checkSub.IndexOf(lowBound)
Dim indexHigh As Integer = checkSub.IndexOf(highBound)
Dim foundLink As String = checkSub.Substring(indexLow + Len(lowBound), indexHigh - Len(highBound))
Console.WriteLine(foundLink)
intCounter = intCounter + (Len(lowBound) + Len(highBound) + Len(foundLink) - 1)
Else
intCounter = Len(pageText)
End If
Loop
Console.ReadLine()
myReader.Close()
My.Computer.FileSystem.DeleteFile("C:\~\VisualStudio\BeginnerPractice\TextFileDotCom_GrabLinkNames\TextFileDotCom_GrabLinkNames\bin\debug\directory.html")
End Sub
End Module

How To Display Image Into Devexpress GridView / Devexpress Card View From Mysql

Here I would like to ask, how to display the image data into DevExpress DevExpress gridview or CardView.
For I will take a picture of data from mysql database that I keep with BLOB data type.
how or its code if using visual basic.?
for Code that I use:
Dim Query As String = "SELECT FTO.ALM_NIM as FOTO_ID, FTO.ALM_FOTO as FOTO FROM tbl_foto_alumni as FTO"
Using DA As New MySql.Data.MySqlClient.MySqlDataAdapter(Query, MyKonection)
Dim DTwisda As New DataTable
DA.Fill(DTwisda)
if Dtwisda.Rows.Count > 0 Then
GridControl.Datasource = DTwisda
MainView = CardView1
Dim RepItemImg As New Repository.RepositoryItemPictureEdit()
RepItemImg.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Stretch
RepItemImg.BestFitWidth = 100
RepItemImg.CustomHeight = 150
With CardView1.Columns("FOTO")
.ColumnEdit = RepItemImg
End With
With CardView1
.OptionsBehavior.FieldAutoHeight = True
.MaximumCardRows = 2
.MaximumCardColumns = 6
End With
End If
End Using
To Screnshoot my program and the results of calling the data from the database, Please Check The Attachment.
already I attach the following word file.
ScreenShoot_Program
Please Help and Give The Solution.
Regards,
Tafary
Try This Code:
Dim row As DataRow
Dim i As Integer
For Each row In myDt.Rows
Column = New DataColumn
With Column
.DataType = GetType(Bitmap)
' .DefaultValue = Base64ToImage(row("Photo"))
.Unique = False
.ColumnName = "EmpPhoto"
End With
If Not myDt.Columns.Contains("EmpPhoto") Then
myDt.Columns.Add(Column)
End If
myDt.Rows(i)("EmpPhoto") = Base64ToImage(row("Photo"))
i += 1
myDt.AcceptChanges()
Next
i = 0
'myDt.Rows.Add(Column.DefaultValue)
Public Function Base64ToImage(base64String As String) As Image
Try
' Convert Base64 String to byte[]
Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)
' Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length)
Dim image1 As Image = Image.FromStream(ms, True)
Return image1
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Function

Not able to open email attachment from bytes array

I am trying to attach a binary data retrieved from MySQL server to an email as attachment using VB.net.
I can send out a email with attachment but not able to open any of the attachment file even word file also is empty.
The error message is --> Adobe Reader could not open "xxx.pdf" because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded).
Been googled around but still not able to find out what is wrong with my code.
Anyone can help will be very appreciated!Thanks!
Dim m_ImageBinary As [Byte]() = New [Byte](-1) {}
Dim m_AttachmentType As String = ""
Dim m_AttachmentName As String = ""
Dim m_Attachment As Boolean = False
Dim cmd3 As New MySqlCommand("SELECT Attachment, AttachmentType, AttachmentName FROM tbcommunication WHERE CommunicationID = " & cid, MySql)
Dim rdr2 As MySqlDataReader = cmd3.ExecuteReader()
While rdr2.Read()
If rdr2("Attachment").ToString() <> "" Then
Dim m_Length As Integer = DirectCast(rdr2("Attachment"), [Byte]()).Length
m_ImageBinary = New [Byte](m_Length - 1) {}
m_ImageBinary = DirectCast(rdr2("Attachment"), [Byte]())
m_AttachmentType = rdr2("AttachmentType").ToString()
m_AttachmentName = rdr2("AttachmentName").ToString()
End If
End While
If m_ImageBinary.Length <> 0 Then
If m_Attachment = False Then
If m_AttachmentType.Contains("jpeg") OrElse m_AttachmentType.Contains("bmp") OrElse m_AttachmentType.Contains("gif") Then
m_Attachment = False
Else
m_Attachment = True
End If
End If
If m_Attachment = True Then
' If not image file
Response.AppendHeader("content-disposition", "attachment; filename=" & m_Atta`enter code here`chmentName)
End If
'Write(binary)
'Response.ContentType = m_AttachmentType
'Response.BinaryWrite(m_ImageBinary)
'Response.[End]()
End If
Dim mailmssg As New MailMessage()
Dim smtp_client As New SmtpClient
Using memoryStream As New MemoryStream()
Dim bytes As Byte() = memoryStream.ToArray()
Dim att As New Attachment(New MemoryStream(bytes), m_AttachmentName)
mailmssg.Attachments.Add(att)
MemoryStream.Dispose()
smtp_client.DeliveryMethod = SmtpDeliveryMethod.Network
smtp_client.Send(mailmssg)
End Using
'...
' memoryStream = new blank MemoryStream
Using memoryStream As New MemoryStream()
' get emtpy array from memoryStream
Dim bytes As Byte() = memoryStream.ToArray()
' Create empty MemoryStream from empty bytes array
Dim att As New Attachment(New MemoryStream(bytes), m_AttachmentName)
'...
With your current code you'll never send anything than an empty file with a name and always only one.

VB .NET server generating Excel file on the fly

I have a VB .NET web application running on a server with multiple requests and performance requirements.
I have a function that retrieves some data from a DB and has to generate an excel report to show to the system users.
I somehow did it, but my solution has not the performance I'd like it to have: basically what my code does is:
The server accepts the request of report generating
The server fills an excel file
The server saves locally the xls file
The server attaches the file to the html response and the user downloads it
The server deletes the file (when? I need to handle borderline cases too)
The code snippet is like:
Public Sub ExportaDataTableToExcel(ByVal dt As System.Data.DataTable, ByVal Page As System.Web.UI.Page, ByVal ReportName As String)
Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim colIndex As Integer
Dim rowIndex As Integer
oExcel = New Excel.Application
oBook = oExcel.Workbooks.Add(Type.Missing)
oSheet = oBook.Worksheets(1)
'Export the Columns to excel file
For Each dc In dt.Columns
colIndex = colIndex + 1
oSheet.Cells(1, colIndex) = dc.ColumnName
Next
oBook.SaveAs("C:\file.xls")
oSheet = Nothing
oBook.Close()
Page.Response.AddHeader("content-disposition", "attachment;filename=" & ReportName & ".xls")
Page.Response.Charset = String.Empty
Page.Response.ContentType = "vnd.application/ms-excel"
Page.Response.TransmitFile("C:\file.xls")
Page.Response.Flush()
Page.Response.End()
oExcel.Quit()
End Sub
As you can see the server generates the xls file locally in C:\file.xls, then trasmittes the file in the response page.
What I'd like to do, and I really don't know if it's possible as I did not found any example on this, is generating the xls file on the fly without saving it locally (maybe returning as a Stream of bytes or something like this) and then assembling this as xls file in the response page, without saving the file locally.
I tried using both Page and System.IO.StringWriter with no luck, maybe I'm doing something wrong.
The following code acts abnormally, asking me to save modifies on the file (on the server side), and downloading an xls file that has parts of the html of the page, generating errors about missing css files and displaying part of the page. So, with this approach I'm almost at zero. Here it is the code:
Public Sub ExportaDataTableToExcel(ByVal dt As System.Data.DataTable, ByVal Page As System.Web.UI.Page, ByVal ReportName As String)
Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim colIndex As Integer
Dim rowIndex As Integer
oExcel = New Excel.Application
oBook = oExcel.Workbooks.Add(Type.Missing)
oSheet = oBook.Worksheets(1)
'Export the Columns to excel file
For Each dc In dt.Columns
colIndex = colIndex + 1
oSheet.Cells(1, colIndex) = dc.ColumnName
Next
oSheet = Nothing
oBook.Close()
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
Dim htmlWrite As System.Web.UI.Html32TextWriter = New System.Web.UI.Html32TextWriter(stringWrite)
Page.Response.Clear()
Page.Response.AddHeader("content-disposition", "attachment;filename=" & ReportName & ".xls")
Page.Response.Charset = String.Empty
Page.Response.ContentType = "vnd.application/ms-excel"
Page.Response.WriteFile(stringWrite.ToString)
Page.Response.Flush()
Page.Response.End()
oExcel.Quit()
End Sub
I know I can help with at least one of those problems you are having, Lateralus. Ive taken a snippet from our live server here to show you.
Edit: This one transmits a CSV file and we had the problem initially with the HTML showing up in the file. We opted to not use excel in this particular instance but, the problems are likely one in the same.
I believe that you need to add an additional header to your page response in order to remove the HTML that you are getting in the file.
Here is an example. As a warning, I'm not entirely sure how secure this method is. We use this within our network so it didn't need to be as locked down.
Dim LiveFileStream As FileStream = New FileStream("C:\inetpub\wwwroot\" &_
"Website\CSVFile.csv", FileMode.Open, FileAccess.Read)
Dim fileBuffer(CInt(LiveFileStream.Length)) As Byte
LiveFileStream.Read(fileBuffer, 0, CInt(LiveFileStream.Length))
LiveFileStream.Close()
Response.Clear()
Response.Charset = "utf-8"
Response.ContentType = "text/plain"
'I believe if you are to add the following header
'it will fix the problem with HTML showing in document
Response.AddHeader("Content-Length", fileBuffer.Length.ToString)
Response.AddHeader("Content-Disposition", "attachment; filename=CSVFile.csv")
Response.BinaryWrite(fileBuffer)
Response.End()

Mysql & Vb.net 'Invalid Attempt to Read when reader is closed'

I have run into this error while collecting data from a mysql database and placing it into a DataView control... This is my code:
Private Function PopulateActivity()
Dim loginStatement As String = "SELECT * FROM activity WHERE id = #userid"
Dim cmd As MySqlCommand = New MySqlCommand(loginStatement, mainconn)
cmd.Parameters.AddWithValue("#userid", LoggedInUser.ID)
Dim drMyAcount As MySqlDataReader = cmd.ExecuteReader()
Dim rowCount As Integer = 0
Dim rowAmount As Integer = 0
'gets count of rows returned from mysql query'
Using dt As New DataTable
dt.Load(drMyAcount)
rowAmount = dt.Rows.Count
End Using
'adds an entry for each item returned from the mysql query'
Do While rowCount < rowAmount
drMyAcount.Read() 'HERE IS WHERE ERROR OCCURS'
Dim tempDateTime As String = drMyAcount.Item("dateTime")
Dim tempInfo As String = drMyAcount.Item("info")
Dim tempBalChanges As String = drMyAcount.Item("balChange")
Dim tempToFrom As String = drMyAcount.Item("toFrom")
ActivityView.Rows.Add(tempDateTime, tempInfo, tempBalChanges, tempToFrom)
rowCount = rowCount + 1
Loop
drMyAcount.Close()
Return 0
End Function
I am unaware of why this is but it gives me an 'Invalid Attempt to Read when reader is closed' error one the:
drMyAccount.Read()
line...
I would appreciate any help on this topic! Thanks Much...
take out the dt.Load() , and counting of the rows prior to using datareader. DataReader has a built in property of .HasRows
if (drMyAcount.HasRows)
while (drMyAcount.Read())
Dim tempDateTime As String = drMyAcount.Item("dateTime")
Dim tempInfo As String = drMyAcount.Item("info")
Dim tempBalChanges As String = drMyAcount.Item("balChange")
Dim tempToFrom As String = drMyAcount.Item("toFrom")
ActivityView.Rows.Add(tempDateTime, tempInfo, tempBalChanges, tempToFrom)
rowCount = rowCount + 1 //you can still count rows in the loop
Loop
The MSDN documentation does not seem to specify, but apparently the DataTable.Load method closes the given IDataReader when it is done loading the data into the table. So, once you call dt.Load(drMyAcount), the drMyAcount will be closed.