having problem with reading docx and pptx files from access attachmant field - vb.net

I have a program that stores files in a attachment field in access database.
Here's the code I use to insert files:
Imports Microsoft.Office.Interop.Access.Dao
Private Sub insert_file(ByVal path As String)
Dim dbe As New DBEngine
Dim db As Database = dbe.OpenDatabase(My.Application.Info.DirectoryPath &"\Mydatabase.accdb")
Dim rstrecord As Recordset = db.OpenRecordset("select * from tblfiles where id=1", RecordsetTypeEnum.dbOpenDynaset)
rstrecord.Edit()
Dim rstattachments As Recordset2 = rstrecord.Fields("File").Value
rstattachments.AddNew()
Dim attachmentdata As Field2 = rstattachments.Fields("FileData")
attachmentdata.LoadFromFile(path)
rstattachments.Update()
rstattachments.Close()
rstrecord.Update()
rstrecord.Close()
db.Close()
End Sub
and I have a option to export the files.Here is the code:
Private Sub export(ByVal id As Integer, ByVal filestr As String, path As String)
DS.Reset()
con = New OleDbConnection(strcon)
con.Open()
cmdtxt = "SELECT ID, File.FileName,File.FileType, File.FileData FROM tblfiles where ID=" & id & " and File.FileName = '" & filestr & "' "
DA = New OleDbDataAdapter(cmdtxt, con)
DA.Fill(DS, "tblfiles")
con.Close()
Dim savestr As String = path
Dim byt() As Byte = DS.Tables("tblfiles").Rows(0).Item("File.FileData")
Try
File.WriteAllBytes(savestr, byt)
MessageBox.Show(File exported successfully)
Catch ex As Exception
messagebox.show(ex.message)
End Try
End Sub
There is no error in inserting and exporting files but when I export pptx and docx files and I open them I receive the following messages:
docx:The file is corrupt and can not be open.
pptx:powerpoint found a problem with content in file.powerpoint can attempt to repair the presentation.

Related

Issue with data type importing csv file into sql in vb.net (SqlBulkCopy)

I'm trying to automate the import of csv data into sql. All files, but one are imported ok, so there is no issue with the code. This particular file has a mixed data type column. And when importing data, it loads data as Double, instead of String. As a result, the values that have words, are imported as null. I tried to convert that column into String (ds.Tables(0).Columns(4).DataType), but it makes no difference. When I try to check the type right after the conversion attempt, it shows runtime type, not a string. I have spent a few days researching similar issues and tried everything I could find. Hopefully someone here can offer help on converting the column properly, as it doesn't work for me. Please see the code below. Thanks!
Private Sub ImportIntoSqlBulk(SqlConnString As SqlConnection, ConnStringSql As String, TableNameSql As String, Filenmcsv As String)
SqlConnString.ConnectionString = ConnStringSql
SqlConnString.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SqlConnString)
bulkCopy.DestinationTableName = TableNameSql
Try
bulkCopy.WriteToServer(GetCsvData(PathImpt, Filenmcsv))
SqlConnString.Close()
Catch ex As Exception
Email_Subject = "Financial Data Import from Excel Error"
successflag = "N"
Email_Body = "There was an error importing data into " & TableNameSql & " from excel. Error message: " & ex.Message
Send_Email()
SqlConnString.Close()
Exit Sub
End Try
End Using
End Sub
Public Function GetCsvData(ByVal strFolderPath As String, ByVal strFileName As String) As DataTable
Dim strConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFolderPath & ";Extended Properties=""Text;HDR=YES;IMEX=1"""
Dim strConnString2 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFolderPath & ";Extended Properties=""Text;HDR=YES;IMEX=1;MaxScanRows=0"""
Dim conn2 As New OleDbConnection(strConnString2)
Dim conn As New OleDbConnection(strConnString)
Try
conn.Open()
Dim cmd As New OleDbCommand("SELECT * FROM [" & strFileName & "]", conn)
Dim da As New OleDbDataAdapter()
da.SelectCommand = cmd
Dim ds As New DataSet()
da.Fill(ds)
If strFileName = "CheckRegister.csv" Then
Convert.ToString(ds.Tables(0).Columns(4).DataType)
ds.Tables(0).Columns(4).DataType.GetType()
End If
da.Dispose()
Return ds.Tables(0)
Catch ex As Exception
Return Nothing
Finally
conn.Close()
End Try
End Function

vb.net if database not found open a OpenFileDialog

I use following code to set a connection to my database: Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb")
I wanted to extent this function by checking if the database exists and If NOT to open a FileOpenDialog to choose another database in another folder. I cant seem to get it to work because when I place the FileOpenDialog on my Main form it throws an Exception error.
Public Function Jokendb() As OleDbConnection
Dim FileName As String = Application.StartupPath & "\FileRename v5.4.accdb"
If IO.File.Exists(FileName) Then
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb")
Else
'Dim result As DialogResult = OpenFileDialog1.ShowDialog()
Dim str As String = OpenFileDialog1.FileName.ToString()
'If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
' Get the file name.
Dim path As String = OpenFileDialog1.FileName
Try
' Read in text.
Dim text As String = File.ReadAllText(path)
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & text)
Catch ex As Exception
' Report an error.
Me.Text = "Error"
End Try
'End If
End If
End Function
I don't know why those line are comented but i think your code could work with these changes:
Public Function Jokendb() As OleDbConnection
Dim FileName As String = Application.StartupPath & "\FileRename v5.4.accdb"
If IO.File.Exists(FileName) Then
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb")
Else
OpenFileDialog1.ShowDialog()
'Dim str As String = OpenFileDialog1.FileName.ToString()
'If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
' Get the file name.
Dim path As String = ""
If OpenFileDialog1.filename <> "" Then
path = OpenFileDialog1.FileName
End If
Try
' Read in text.
Dim text As String = File.ReadAllText(path)
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & text)
Catch ex As Exception
' Report an error.
Me.Text = "Error"
End Try
'End If
End If
End Function

Set datasource of datagridview in module

I am writing a program that will automatically process files, based on a set of criteria. In order to process these, I need to load the Excel file first, before I can process it.
I create a module called "NewBusAuto". In here, I created a new datagridview. I am trying to set the datasource of this, but whenever I do, it doesn't actually bind. When I try and process each row/column, it is saying it is still empty.
Code used:
Module m_NewBusinessAutomation
Dim dgvImport As DataGridView
Public Sub NewBusAuto(ByVal folderName As String,
ByVal fileName As String,
ByVal executeScript As String)
dgvImport = New DataGridView
If Path.GetExtension(fileName) = ".xls" Or Path.GetExtension(fileName) = ".xlsx" Then
Using cn As New System.Data.OleDb.OleDbConnection
Dim builder As New OleDbConnectionStringBuilder With _
{.DataSource = folderName & "\" & fileName,
.Provider = "Microsoft.ACE.OLEDB.12.0"}
builder.Add("Extended Properties", "Excel 12.0; IMEX=1;HDR=Yes;")
cn.ConnectionString = builder.ConnectionString
cn.Open()
Using cmd As OleDbCommand = New OleDbCommand With {.Connection = cn}
cmd.CommandText = "SELECT * FROM [Sheet1$]"
Dim dr As System.Data.IDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
dgvImport.DataSource = dt
dgvImport.Refresh()
Messagebox.show(dgvImport.RowCount & "-" & dgvImport.ColumnCount)
dr.Close()
End Using
End Using
End If
The messagebox is giving me "0 - 0" as a result.
I need to load the Excel file to the actual database. Any help would be appreciated!

Prevent Excel pop up message in VB code

I am having a problem with the "File Now Available" message box popping open from excel when i importing a file to my program.
http://oi50.tinypic.com/23wajt.jpg
Private Function XLSSelect_Click(strFileName As String) As DataTable
Dim connectionStringTemplate As String = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"""
Dim connectionString As String = String.Format(connectionStringTemplate, strFileName)
Try
Dim sqlSelect As String = "SELECT * FROM [" & GetExcelSheetNames(strFileName)(0) & "];"
' Load the Excel worksheet into a DataTable
Dim workbook As DataSet = New DataSet()
Dim excelAdapter As System.Data.Common.DataAdapter = New System.Data.OleDb.OleDbDataAdapter(sqlSelect, connectionString)
excelAdapter.Fill(workbook)
For i As Integer = 0 To workbook.Tables(0).Columns.Count - 1
workbook.Tables(0).Columns(i).ColumnName = workbook.Tables(0).Columns(i).ColumnName.ToString.Trim.Replace(" ", "")
Next
Return workbook.Tables(0).Copy
Catch
Throw New Exception("Error reading from Excel Spreadsheet. Are you sure this file isn't currently open in Excel, and that it has been saved as a .xls through Excel at least once?")
End Try
Return Nothing
End Function
Private Shared Function GetExcelSheetNames(excelFile As String) As [String]()
Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Try
Dim connString As [String] = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & excelFile & ";Extended Properties=Excel 12.0;"
' Create connection object by using the preceding connection string.
objConn = New OleDbConnection(connString)
' Open connection with the database.
objConn.Open()
' Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}
Dim i As Integer = 0
'Add the sheet name to the string array.
For Each row As DataRow In dt.Rows
excelSheets(i) = row("TABLE_NAME").ToString()
i += 1
Next
Return excelSheets
Catch ex As Exception
Return Nothing
Finally
' Clean up.
If objConn IsNot Nothing Then
objConn.Close()
objConn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try
End Function
Anyone know how i can go about disabling this ?
Dim appExcel As Excel.Application
Set appExcel = New Excel.Application
appExcel.Workbooks.Open "e:\development\test.xls", 0
' Do your thing here...
appExcel.DisplayAlerts = False ' Surpress save dialog box.
appExcel.Quit ' Quit without saving. you can change as you want
Set appExcel = Nothing
in your code
Try
Dim connString As [String] = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & excelFile & ";Extended Properties=Excel 12.0;"
' Create connection object by using the preceding connection string.
objConn = New OleDbConnection(connString)
' Open connection with the database.
objConn.Open()
appExcel.DisplayAlerts = False ' try here!
' Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Sources : http://www.xtremevbtalk.com/showthread.php?t=16007

failed to read the excel to sql database

I want to upload an Excel file and write data to sql server 2008.
The Excel file has 7 sheets and it writes in 7 tables.
Example : (sheetn -> temp_sheetn)
The code is working well but the last sheet is not writing in the last table.
The code is like this:
Partial Class app_UploadData
Inherits System.Web.UI.Page
Dim apps As New MyApps
Dim GlobReg As Integer = 0
Dim GlobOTC As Integer = 0
Private dt As DataTable = Nothing
Public Function xlsInsert(ByVal pth As String) As System.Data.DataTable
Dim strcon As String = String.Empty
If Path.GetExtension(pth).ToLower().Equals(".xls") OrElse Path.GetExtension(pth).ToLower().Equals(".xlsx") Then
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & pth & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Else
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & pth & ";Extended Properties=""Excel 12.0;HDR=YES;"""
End If
Dim strselect As String = "Select * from [Sheet1$]"
Dim exDT As New DataTable()
Using excelCon As New OleDbConnection(strcon)
Try
excelCon.Open()
Using exDA As New OleDbDataAdapter(strselect, excelCon)
exDA.Fill(exDT)
End Using
Catch oledb As OleDbException
Throw New Exception(oledb.Message.ToString())
Finally
excelCon.Close()
End Try
For i As Integer = 0 To exDT.Rows.Count - 1
' Check if first column is empty
' If empty then delete such record
If exDT.Rows(i)("CardNo").ToString() = String.Empty Then
exDT.Rows(i).Delete()
End If
Next
exDT.AcceptChanges()
' refresh rows changes
If exDT.Rows.Count = 0 Then
Throw New Exception("File uploaded has no record found.")
End If
Return exDT
End Using
End Function
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim ds As New DataSet()
Dim XlsConnString As String = String.Empty
Dim DirPath As String = Server.MapPath("~/Temp_Upload/")
Dim fName As String
If (Directory.Exists(DirPath)) Then
For Each fName In Directory.GetFiles(DirPath)
If File.Exists(fName) Then
File.Delete(fName)
End If
Next
End If
If xlsUpload.HasFile Then
Dim fileName As String = Path.GetFileName(xlsUpload.PostedFile.FileName)
Dim fileExtension As String = Path.GetExtension(xlsUpload.PostedFile.FileName)
Dim fileLocation As String = Server.MapPath("~/Temp_Upload/" & fileName)
xlsUpload.SaveAs(fileLocation)
'Check whether file extension is xls or xslx
If fileExtension = ".xls" Then
XlsConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension = ".xlsx" Then
XlsConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension <> ".xls" Or fileExtension <> ".xlsx" Then
lblMessage.Text = "Upload file must be excel !"
Exit Sub
End If
Dim cmd As New SqlCommand : Dim SheetName As String 'Dim dr As SqlDataReader
'Dim tran As SqlTransaction
apps.OpenConnection()
cmd.Connection = apps.oConn
Dim cn As New OleDbConnection(XlsConnString)
Try
cn.Open()
Catch ex As OleDbException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
' It Represents Excel data table Schema.
Dim dt As New System.Data.DataTable()
dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt IsNot Nothing OrElse dt.Rows.Count > 0 Then
For sheet_count As Integer = 1 To dt.Rows.Count - 1
Try
' Create Query to get Data from sheet.
SheetName = dt.Rows(sheet_count)("table_name").ToString()
'Dim da As New OleDbDataAdapter("SELECT * FROM [" & sheetname & "]", cn)
'da.Fill(ds, sheetname)
'Execute a query to erase any previous data from our destination table
cmd.CommandText = "Truncate Table Temp_" & SheetName
cmd.ExecuteNonQuery()
'Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(XlsConnString)
Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [" & SheetName & "]"), OleDbConn)
'Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [Customer$]"), OleDbConn)
OleDbConn.Open()
Dim OleDbRead As OleDbDataReader = OleDbCmd.ExecuteReader()
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(apps.oConn)
bulkCopy.DestinationTableName = "Temp_" & SheetName
bulkCopy.WriteToServer(OleDbRead)
OleDbConn.Close()
OleDbConn = Nothing
Catch ex As DataException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Next
End If
cn.Close()
cn = Nothing
apps.CloseConnection()
End If
End Sub
End Class
The line that reads
For sheet_count As Integer = 1 To dt.Rows.Count - 1
should either be
For sheet_count As Integer = 0 To dt.Rows.Count - 1
or
For sheet_count As Integer = 1 To dt.Rows.Count
The first one I suspect, but I can't remember if this is a zero based list as I haven't got VB.Net installed here.
Incidentally there's no need to check the file extension is .xls and then to use the Jet provider, Microsoft.ACE.OLEDB.12.0 will work just fine on .xls files.