I have a ms access database with an ole object field where I have pasted in images collected from various places from the internet, no files created before copying them into the field
the database has got rather large and I want to export the images to a file and link them rather than embed them
I have got this far
Public Function exportlink()
Dim strSQL As String
Dim mstream As ADODB.Stream
Dim strFullPath As String
Dim image As Control
Dim FN As String
Set image = Forms!frmuseful!image
strFullPath = "C:\Documents\pics\"
FN = Forms!frmuseful!ID & "a" & ".jpg"
'Create a Stream Object to contain the Binary Data from the OLE Object Field,
'(adTypeBinary), then Open it
Set mstream = New ADODB.Stream
mstream.Type = adTypeBinary
mstream.Open
'Write the contents of the OLE Object Field to the Stream
mstream.Write image.Value
mstream.SaveToFile strFullPath & FN, adSaveCreateOverWrite
End Function
which outputs a file but when I try to open it it says not a valid JPG file. size wise it looks more like what I could expect for a bitmap file, but changing to .bmp also gives not a valid BMP file.
I am guess that somewhere along the line I need to convert the stream to jpg format, but I am not sure how to do that
Related
Okay my website generates thousands of PDFs using RDLCs but my problem is sometimes I want to email them but I don't want to attach a PDF to an email. So what I need is a way to generate the report then either convert it into text or html so I can send it as the body of an email.
Also I am using reportviewr version 11
Also I have tried exporting it as a .doc then trying to convert it to text and i have tried to export it to an excel document then tried to convert it and none of it works.
Dim warn() As Warning = Nothing
Dim streamids() As String = Nothing
Dim mimeType As String = String.Empty
Dim encoding As String = String.Empty
Dim extension As String = String.Empty
Dim bytes() As Byte
bytes = rv.LocalReport.Render("MHTML", Nothing, mimeType, encoding, extension, streamids, warn)
'Only one copy of the notice is needed
'If Not Directory.Exists(strFilePath) Then Directory.CreateDirectory(strFilePath)
Dim fs As New FileStream(strFilePath, FileMode.Create)
fs.Write(bytes, 0, bytes.Length)
fs.Close()
here is the code i'm using but it gives me an error : Specified argument was out of the range of valid values. Parameter name: format
Also i know this code works because I use the exact same thing to export the rdlc to a PDF
Ok so I solved my own problem with some Research about bytes.
Here is the code that I used to solve my problem.
What I did was exported the reportviewr as a word document and then converted all bytes to text. Then from that you end up with a whole bunch of gibberish but eventually you will find the text from your RDLC. So what I did was split the string up to where I was only left with the wording from my RDLC.
Review the code below:
Function GetRDLCText(ByVal rv As ReportViewer) As String
Dim warn() As Warning = Nothing
Dim streamids() As String = Nothing
Dim mimeType As String = String.Empty
Dim encoding As String = String.Empty
Dim extension As String = String.Empty
Dim bytes() As Byte
Dim msg() As String
bytes = rv.LocalReport.Render("WORD", Nothing, mimeType, encoding, extension, streamids, warn)
'Word is the only export that contains text from the rdlc
Dim content As String = System.Text.Encoding.Unicode.GetString(bytes)
msg = content.Split("Ù")
msg = msg(1).Split("Ѐ")
Return msg(0)
End Function
This solution is not for everyone, but it works for what I need it to do.
I'm writing a query to extract text that was entered through a vendor-created word processor to an Oracle database and I need to export it to Word or Excel. The text is entered into a memo field and the text is intertwined with codes that the word processor uses for different functions (bold, indent, hard return, font size, etc.).
I've used the replace function to parse out a lot of the more common codes, but there are so many variations, it's nearly impossible to catch them all. Is there a way to do this? Unfortunately, I'm limited to using Microsoft Access 2010 to try and accomplish this.
The common thread I've found is that all the codes start with a back-slash and I'd like to be able to delete all strings that start with a back-slash up to the next space so all the codes are stripped out of the final text.
Here's a brief example of the text I'm working with:
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Times New Roman;
\viewkind4\uc1\pard\f0\fs36 An abbreviated survey was conducted
on 02/02/15 to investigate complaint #OK000227. \par
No deficiencies were cited.\par
\fs20\par
}}
If your machine has Microsoft Word installed then you already have an RTF parser available so you don't have to "roll your own". You can just get Word to open the RTF document and save it as plain text like this:
Option Compare Database
Option Explicit
Public Function RtfToPlainText(rtfText As Variant) As Variant
Dim rtn As Variant
Dim tempFolder As String, rtfPath As String, txtPath As String
Dim fso As Object ' FileSystemObject
Dim f As Object ' TextStream
Dim wordApp As Object ' Word.Application
Dim wordDoc As Object ' Word.Document
Dim tempFileName As String
tempFileName = "~RtfToPlainText"
If IsNull(rtfText) Then
rtn = Null
Else
' save RTF text as file
Set fso = CreateObject("Scripting.FileSystemObject")
tempFolder = fso.GetSpecialFolder(2) ' Temporaryfolder
rtfPath = tempFolder & "\" & tempFileName & ".rtf"
Set f = fso.CreateTextFile(rtfPath)
f.Write rtfText
f.Close
Set f = Nothing
' open in Word and save as plain text
Set wordApp = CreateObject("Word.Application")
Set wordDoc = wordApp.Documents.Open(rtfPath)
txtPath = tempFolder & "\" & tempFileName & ".txt"
wordDoc.SaveAs2 txtPath, 2 ' wdFormatText
wordDoc.Close False
Set wordDoc = Nothing
wordApp.Quit False
Set wordApp = Nothing
fso.DeleteFile rtfPath
' retrieve plain text
Set f = fso.OpenTextFile(txtPath)
rtn = f.ReadAll
f.Close
Set f = Nothing
fso.DeleteFile txtPath
Set fso = Nothing
End If
RtfToPlainText = rtn
End Function
Then, if you had a table with two Memo fields - [rtfText] and [plainText] - you could extract the plain text into the second Memo field using the following query in Access:
UPDATE rtfTestTable SET plainText = RtfToPlainText([rtfText]);
The text you are working with is RTF. Here is a tutorial about the file format.
This link (on another site, registration required) may give you copy & paste code you can use to convert rtf fields to txt.
You may be able to copy the value of the field from the database and paste it into notepad and then save the notepad file as "test.rtf"...you could then double click the file icon and the document may open.
RTF is an old MS file format that allows formatting of text. See this wikipedia page.
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()
Background Information:
I am not very savvy with VBA, or Access for that matter, but I have a VBA script that creates a file (a KML to be specific, but this won't matter much for my question) on the users computer and writes to it using variables that link to records in the database. As such:
Dim MyDB As Database
Dim MyRS As Recordset
Dim QryOrTblDef As String
Dim TestFile As Integer
QryOrTblDef = "Table1"
Set MyDB = CurrentDb
Set MyRS = MyDB.OpenRecordset(QryOrTblDef)
TestFile = FreeFile
Open "C:\Testing.txt"
Print #TestFile, "Generic Stuff"
Print #TestFile, MyRS.Fields(0)
etc.
My Situation:
I have a very large string(a text document with a large list of polygon vertex coordinates) that I want to add to a variable to be printed to another file (a KML file, noted in the above example). I was hoping to add this text file containing coordinates as an attachment datatype to the Access database and copy its contents into a variable to be used in the above script.
My Question:
Is there a way I can access and copy the data from an attached text file (attached as an attachment data type within a field of an MS Access database) into a variable so that I can use it in a VBA script?
What I have found:
I am having trouble finidng information on this topic I think mainly because I do not have the knowledge of what keywords to be searching for, but I was able to find someones code on a forum, "ozgrid", that seems to be close to what I want to do. Though it is just pulling from a text file on disk rather than one attached to the database.
Code from above mentioned forum that creates a function to access data in a text file:
Sub Test()
Dim strText As String
strText = GetFileContent("C:\temp\x.txt")
MsgBox strText
End Sub
Function GetFileContent(Name As String) As String
Dim intUnit As Integer
On Error Goto ErrGetFileContent
intUnit = FreeFile
Open Name For Input As intUnit
GetFileContent = Input(LOF(intUnit), intUnit)
ErrGetFileContent:
Close intUnit
Exit Function
End Function
Any help here is appreciated. Thanks.
I am a little puzzled as to why a memo data type does not suit if you are storing pure text, or even a table for organized text. That being said, one way is to output to disk and read into a string.
''Ref: Windows Script Host Object Model
Dim fs As New FileSystemObject
Dim ts As TextStream
Dim rs As DAO.Recordset, rsA As DAO.Recordset
Dim sFilePath As String
Dim sFileText As String
sFilePath = "z:\docs\"
Set rs = CurrentDb.OpenRecordset("maintable")
Set rsA = rs.Fields("aAttachment").Value
''File exists
If Not fs.FileExists(sFilePath & rsA.Fields("FileName").Value) Then
''It will save with the existing FileName, but you can assign a new name
rsA.Fields("FileData").SaveToFile sFilePath
End If
Set ts = fs.OpenTextFile(sFilePath _
& rsA.Fields("FileName").Value, ForReading)
sFileText = ts.ReadAll
See also: http://msdn.microsoft.com/en-us/library/office/ff835669.aspx
I'm busy with an applicaton which reads space delimited log files ranging from 5mb to 1gb+ in size, then stores this information to a MySQL database for later use when printing reports based upon the information contained in the files. The methods I've tried / found work but are very slow.
Am I doing something wrong? or is there a better way to handle very large text files?
I've tried using textfieldparser as follows:
Using parser As New TextFieldParser("C:\logfiles\testfile.txt")
parser.TextFieldType = FieldType.Delimited
parser.CommentTokens = New String() {"#"}
parser.Delimiters = New String() {" "}
parser.HasFieldsEnclosedInQuotes = False
parser.TrimWhiteSpace = True
While Not parser.EndOfData
Dim input As String() = parser.ReadFields()
If input.Length = 10 Then
'add this to a datatable
End If
End While
End Using
This works but is very slow for the larger files.
I then tried using an OleDB connection to the text file as per the following function in conjunction with a schema.ini file I write to the directory beforehand:
Function GetSquidData(ByVal logfile_path As String) As System.Data.DataTable
Dim myData As New DataSet
Dim strFilePath As String = ""
If logfile_path.EndsWith("\") Then
strFilePath = logfile_path
Else
strFilePath = logfile_path & "\"
End If
Dim mySelectQry As String = "SELECT * FROM testfile.txt WHERE Client_IP <> """""
Dim myConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFilePath & ";Extended Properties=""text;HDR=NO;""")
Dim dsCmd As New System.Data.OleDb.OleDbDataAdapter(mySelectQry, myConnection)
dsCmd.Fill(myData, "logdata")
If Not myConnection.State = ConnectionState.Closed Then
myConnection.Close()
End If
Return myData.Tables("logdata")
End Function
The schema.ini file:
[testfile.txt]
Format=Delimited( )
ColNameHeader=False
Col1=Timestamp text
Col2=Elapsed text
Col3=Client_IP text
Col4=Action_Code text
Col5=Size double
Col6=Method text
Col7=URI text
Col8=Ident text
Col9=Hierarchy_From text
Col10=Content text
Anyone have any ideas how to read these files faster?
-edit-
Corrected a typo in the code above
There are two potentially slow operations there:
File reading
Inserting lots of data into the db
Separate them and test which is taking the most time. I.e. write one test program that simply reads the file, and another test program that just inserts loads of records. See which one is slowest.
One problem could be that you are reading the whole file into memory?
Try reading it line by line with a Stream. Here is a code example copied from MSDN
Imports System
Imports System.IO
Class Test
Public Shared Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As New StreamReader("TestFile.txt")
Dim line As String
' Read and display lines from the file until the end of
' the file is reached.
Do
line = sr.ReadLine()
If Not (line Is Nothing) Then
Console.WriteLine(line)
End If
Loop Until line Is Nothing
End Using
Catch e As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(e.Message)
End Try
End Sub
End Class
From the top of my head id say try to impelement some kind of threading to spread the workload.