Crystal report export in excel - vb.net

Having problem in my crystal report, exporting to excel. Can somebody help me how to code or any suggestion code that will catch if the file you exported is already exist?
For example, you exported lotinfo the next will be lotinfo2 then lotinfo3 etc, my code is always exporting single file and single name.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New _
DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New ExcelFormatOptions
CrDiskFileDestinationOptions.DiskFileName = _
"c:\Lot Enterprise Information.xls"
CrExportOptions = crypt.ExportOptions
With CrExportOptions
.ExportDestinationType = ExportDestinationType.DiskFile
.ExportFormatType = ExportFormatType.Excel
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = CrFormatTypeOptions
End With
crypt.Export()
MessageBox.Show("LOT ENTERPRISE INFORMATION IS SUCCESSFULLY EXPORTED!, LOCATED AT DRIVE C:", "PLEASE CHECK AT DRIVE C:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MsgBox("Please Select Specific date to convert!")
'MsgBox(ex.ToString)
End Try
End Sub

I've been using this function for quite some time now. Just fix it up depending on your use.
Private Function fileExists(ByVal path As String, ByVal filename As String) As String
' This function basically adds a counter when the file already exists
' eg filename
' filename(1)
' filename(2)
Dim counter As Integer = 0
Dim orginialFileName As String = System.IO.Path.Combine(path, filename)
Dim newFileName = orginialFileName
Dim extension As String = ""
Dim testIndex As Integer = 0
While File.Exists(newFileName)
counter = counter + 1
extension = newFileName.Substring(newFileName.LastIndexOf("."))
filename = filename.Substring(0, filename.LastIndexOf("."))
testIndex = filename.LastIndexOf("(")
If testIndex <> -1 Then
filename = filename.Substring(0, testIndex)
End If
newFileName = String.Format("{0}({1})", System.IO.Path.Combine(path, filename), counter.ToString())
filename = String.Format("{0}({1})", filename, counter.ToString())
newFileName += extension
filename += extension
End While
Return filename
End Function
example usage
Dim output as string
output = fileExists("C:\test", "file.xls")
MsgBox(output)
This link might also be useful for you.
EDIT:
You can use it before your Try-Catch block
Dim fullPath As String = "C:\fileinfo.xls"
Dim directory, output, filename As String
If File.Exists(fullPath) Then
directory = fullPath.Substring(0, fullPath.LastIndexOf("\"))
filename = fullPath.Substring(fullPath.LastIndexOf("\") + 1)
output = fileExists(directory, filename)
fullPath = path.combine(directory,output)
End If
Then change this part
CrDiskFileDestinationOptions.DiskFileName = _
"c:\Lot Enterprise Information.xls"
To
CrDiskFileDestinationOptions.DiskFileName = _
fullPath

Related

Making a program that zip files but having error The process cannot access the file because it is being used by another process

I am trying to make a program that will zip all the files in the same folder.
But I'm having issues with it. It's giving me an error saying the file is being used by another process.
Private Sub btnZip_Click(sender As Object, e As EventArgs) Handles btnZip.Click
Dim extension As String = txtExtension.Text
Dim paths As String = Application.StartupPath
Dim files As String() = Directory.GetFiles(paths, "*.*")
For Each file As String In files
Dim fileName As String = path.GetFileNameWithoutExtension(file)
Dim index As Integer = fileName.IndexOf("_")
If index >= 0 Then
fileName = fileName.Substring(0, index)
End If
ZipFile.CreateFromDirectory(Path.GetDirectoryName(file), paths & "\" & fileName & ".zip", CompressionLevel.Optimal, False)
Next
MessageBox.Show("Files zipped successfully!")
End Sub
I just couldn't figure out what's causing the issue.
as seen in comment, you must exclude your running application from the file list :
add
If Path.GetFileName(file) = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Then Continue For
in for loop
Private Sub btnZip_Click(sender As Object, e As EventArgs) Handles btnZip.Click
Dim extension As String = txtExtension.Text
Dim paths As String = Application.StartupPath
Dim files As String() = Directory.GetFiles(paths, "*.*")
For Each file As String In files
If Path.GetFileName(file) = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Then Continue For
Dim fileName As String = Path.GetFileNameWithoutExtension(file)
Dim index As Integer = fileName.IndexOf("_")
If index >= 0 Then
fileName = fileName.Substring(0, index)
End If
ZipFile.CreateFromDirectory(Path.GetDirectoryName(file), paths & "\" & fileName & ".zip", CompressionLevel.Optimal, False)
Next
MessageBox.Show("Files zipped successfully!")
End Sub

How not to overwrite files in VB.net

I want to check if the current file exists at the same time save video to different file but it only overwrites to an existing file.
Here is my code:
Private Sub ButtonVIDEO_Click(ByVal sender As System.Object, e As System.EventArgs) Handles ButtonVIDEO.Click
f = New Filters
cap = New Capture(f.VideoInputDevices(0), f.AudioInputDevices(0))
cap.PreviewWindow = PictureBox1
Dim Filename As String = "c:\\folder\MyFile"
Dim i As Integer = 0
Dim extension As String = ".mp4"
If ButtonVIDEO.BackColor = Color.Black Then
cap.Filename = Filename + extension
If File.Exists(Filename) Then
Do
i = i + 1
Loop While File.Exists(Filename + i.ToString() + extension)
Filename = Filename + i.ToString()
End If
cap.Cue()
cap.Start()
ButtonVIDEO.BackColor = Color.Red
ButtonVIDEO.Text = "PLAYING"
ButtonPHOTO.Hide()
End If
End Sub
You are assigning the file name to cap before searching for an unsused file name.
Also, there is an error in your logic, as you are creating the full file name with Filename + i.ToString() + extension but you also append i to Filename itself with Filename = Filename + i.ToString().
So, in then end, you are appending the number twice.
Private Sub ButtonVIDEO_Click(ByVal sender As System.Object, e As System.EventArgs) _
Handles ButtonVIDEO.Click
Dim Filename As String = "c:\folder\MyFile"
Dim i As Integer = 0
Dim extension As String = ".mp4"
Dim path As String = Filename & extension
f = New Filters
cap = New Capture(f.VideoInputDevices(0), f.AudioInputDevices(0))
cap.PreviewWindow = PictureBox1
If ButtonVIDEO.BackColor = Color.Black Then
If File.Exists(path) Then
Do
i = i + 1
path = Filename & i & extension
Loop While File.Exists(path)
End If
cap.Filename = path
cap.Cue()
cap.Start()
ButtonVIDEO.BackColor = Color.Red
ButtonVIDEO.Text = "PLAYING"
ButtonPHOTO.Hide()
End If
End Sub
The path should have only one backslash in c:\folder. In VB strings are concatenated with &, not +.
See answer to The difference between + and & for joining strings in VB.NET

VB service export SQL to CSV

I have created a service that is supposed to pass data from SQL to CSV, by creating a CSV file. It has no errors, but i run it and nothing happens.
1) Is there something I am missing?
2) If it works, and i want to convert to txt file, is it enough to change the "CSV" to "txt" parts?
My code:
#Region "Export SQL TO CSV"
Public Shared Function WriteCSV(ByVal input As String) As String
Try
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If
i = (i + 1)
Loop
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Else
Return input
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ExtoCsv(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As StringBuilder = New StringBuilder
Using db As Database.RecordSet = admin.Database.OpenRecordsetReadOnly("select USERID, NAME1 from usertable WHERE I_ID=2")
Dim userid As String = db("USERID").Value
Dim name1 As String = db("NAME1").Value
For i As Integer = 1 To db.RecordCount
sb.Append(WriteCSV(userid + "," + name1 + ","))
sb.AppendLine()
db.MoveNext()
Next
End Using
File.WriteAllText("C:\Users\user1\Desktop\ex1.csv", sb.ToString)
If (Not System.IO.Directory.Exists("C:\Users\user1\Desktop\ex1")) Then
System.IO.Directory.CreateDirectory("C:\Users\user1\Desktop\ex1")
End If
End Sub
#End Region

Why does Virtual Basic say it cannot access the file?

I am creating a solid edge macro that saves a 3D file in solid edge in three different types simultaneously.
owever, I am new to vb.net some I am having some difficulty.
When I run the program, the first pop up says "this file already exists, do you want to overwrite it?".
The next pop up says "cannot access this file" and then the program stops.
Why can vb.net not access the file? It is open in solid edge in the background.
Imports System.Runtime.InteropServices
Public Class Form1
Private Sub saveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles saveBtn.Click
Dim objApplication As SolidEdgeFramework.Application = Nothing
Dim objDocument As SolidEdgeFramework.SolidEdgeDocument = Nothing
Dim objPropertySets As SolidEdgeFramework.PropertySets = Nothing
Dim objProperties As SolidEdgeFramework.Properties = Nothing
Dim objProperty As SolidEdgeFramework.Property = Nothing
Dim FileName As String
Dim i, j As Integer
Dim NewFileName1 As String
Dim NewFileName2 As String
Dim NewFileName3 As String
Dim Extensions(2) As String
Extensions(0) = ".step"
Extensions(1) = ".x_t"
Extensions(2) = ".igs"
Try
objApplication = Marshal.GetActiveObject("SolidEdge.Application")
objDocument = objApplication.ActiveDocument
objPropertySets = objDocument.Properties
For i = 1 To objPropertySets.Count
objProperties = objPropertySets.Item(i)
For j = 1 To objProperties.Count
objProperty = objProperties.Item(j)
Next
Next
FileName = objProperty.Name
NewFileName1 = FileName & Extensions(0)
NewFileName2 = FileName & Extensions(1)
NewFileName3 = FileName & Extensions(2)
objDocument.SaveAs("C:\Folder", NewFileName1)
objDocument.SaveAs("C:\Folder", NewFileName2)
objDocument.SaveAs("C:\Folder", NewFileName3)
'objDocument.SaveAs(NewFileName1)
'objDocument.SaveAs(NewFileName2)
'objDocument.SaveAs(NewFileName3)
Catch ex As Exception
txt.Text = " Error"
Finally
If Not (objDocument Is Nothing) Then
Marshal.ReleaseComObject(objDocument)
objDocument = Nothing
End If
If Not (objApplication Is Nothing) Then
Marshal.ReleaseComObject(objApplication)
objApplication = Nothing
End If
End Try
End Sub
End Class

Merge pdf using Docotic.Pdf Library

I already have a class that does this but I want you to finish programming a NEW class using the Docotic.Pdf Library Their website for your reference is: http://bitmiracle.com/pdf-library/
this code which I write.
`Public Class Form1
Private Sub butMergePdfs_Click(sender As System.Object, e As System.EventArgs) Handles butMergePdfs.Click
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Load some sample PDF files into the string arrays
'In production it will read the files into the string arrays
'from a database.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim strMergeFiles(3) As String
Dim strMergeTitles(3) As String
strMergeFiles(0) = "D:\Nayeem_Mansoori\Cis_Projects\Cis_Projects\SanjayVerma\PdfMergeTest\PDF_1.pdf"
strMergeFiles(1) = "D:\Nayeem_Mansoori\Cis_Projects\Cis_Projects\SanjayVerma\PdfMergeTest\PDF_2.pdf"
strMergeFiles(2) = "D:\Nayeem_Mansoori\Cis_Projects\Cis_Projects\SanjayVerma\PdfMergeTest\PDF_3.pdf"
'strMergeFiles(0) = "C:\Temp\PDF_1.pdf"
'strMergeFiles(1) = "C:\Temp\PDF_2.pdf"
'strMergeFiles(2) = "C:\Temp\PDF_3.pdf"
strMergeTitles(0) = "OUTLINE_1"
strMergeTitles(1) = "OUTLINE_2"
strMergeTitles(2) = "OUTLINE_3"
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'This shows how the old class worked. The new class needs to work
'with exactly the same parameters.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Dim myMerge As New clsMerge_OLD
'Dim strFileName As String = System.IO.Path.GetRandomFileName & ".pdf"
'Dim strOutputFileAndPath As String = "C:\temp\" & strFileName
Dim myMerge As New clsMerge_NEW
Dim strFileName As String = System.IO.Path.GetRandomFileName & ".pdf"
Dim strOutputFileAndPath As String = "C:\temp\" & strFileName
'Merge the files.
myMerge.MergeFiles(strMergeFiles, strMergeTitles, strOutputFileAndPath)
'Shop any merge errors.
If myMerge.Errors <> "" Then
MsgBox(myMerge.Errors)
End If
'Open the merged PDF
Process.Start(strOutputFileAndPath)
myMerge = Nothing
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)
MsgBox(System.IO.Directory.GetCurrentDirectory())
End Sub
End Class
Imports BitMiracle.Docotic.Pdf
Public Class clsMerge_NEW
Private mstrErrors As String
Private mboolCurrentFileIsIrefStream As Boolean
Private mboolPadPageCountToEven As Boolean
Private mRand As Random
Public ReadOnly Property Errors() As String
Get
Return mstrErrors
End Get
End Property
Public Sub New()
mstrErrors = ""
End Sub
Public Function MergeFiles(ByVal SourceFiles() As String _
, ByVal SourceTitles() As String _
, ByVal DestinationFile As String) As Boolean
Dim boolReturnVal As Boolean = True
'clear error variable
mstrErrors = ""
'If the destination merged PDF file exists, then delete it.
Try
If System.IO.File.Exists(DestinationFile) = True Then
System.IO.File.Delete(DestinationFile)
End If
Catch ex As Exception
mstrErrors = mstrErrors & " Cannot delete destination file:" & DestinationFile & ". Error is: " & ex.Message & vbCrLf
boolReturnVal = False
End Try
If boolReturnVal = True Then 'if still true then continue!
'Iterate the string array.
For i As Int32 = 0 To UBound(SourceFiles) - 1
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'
' !!!! FINISH THIS CODE - MERGE THE PDF's !!!!!!!
'
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Ensure OUTLINES are created in the destination PDF file!!!!!
'The TITLES passed in SourceTitles are the OUTLINES.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Next
End If
Return boolReturnVal
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'
' Here is a C# example of how to use the class.
'
'-------------------------------------------------------------------------------
'
' using (PdfDocument pdf = new PdfDocument())
' {
' pdf.PageMode = PdfPageMode.UseOutlines;
' pdf.Append("d:\\0000-2981A.pdf");
'
' pdf.Append("d:\\0000-2981B.pdf");
' pdf.RemovePage(0);
'
'
' PdfOutlineItem root = pdf.OutlineRoot;
'
' for (int i = 0; i < pdf.PageCount; ++i)
' {
' int pgcount = i + 1;
' PdfOutlineItem outlineForPage = root.AddChild("Page " + pgcount.ToString(), i);
' }
'
' pdf.Save(pathToFile);
' }
End Class
Please can any one help me.
Your question could be more specific. I am not sure I understood it right, but please try following sample code.
The sample code combines different documents into one PDF file and creates bookmarks. Each bookmark points to the first page of original document. Bookmarks titles are provided as parameter to the function.
Please note that the code is auto-converted from C#.
Public Shared Sub MergeFiles(sourceFiles As String(), bookmarkTitles As String(), destination As String)
Using pdf As New PdfDocument()
Dim targetPageIndex As Integer = 0
For i As Integer = 0 To sourceFiles.Length - 1
Dim currentName As String = sourceFiles(i)
If i = 0 Then
pdf.Open(currentName)
Else
pdf.Append(currentName)
End If
pdf.OutlineRoot.AddChild(bookmarkTitles(i), targetPageIndex)
targetPageIndex = pdf.PageCount
Next
pdf.PageMode = PdfPageMode.UseOutlines
pdf.Save(destination)
End Using
End Sub
Here is the C# version for the reference:
public static void MergeFiles(string[] sourceFiles, string[] bookmarkTitles, string destination)
{
using (PdfDocument pdf = new PdfDocument())
{
int targetPageIndex = 0;
for (int i = 0; i < sourceFiles.Length; i++)
{
string currentName = sourceFiles[i];
if (i == 0)
pdf.Open(currentName);
else
pdf.Append(currentName);
pdf.OutlineRoot.AddChild(bookmarkTitles[i], targetPageIndex);
targetPageIndex = pdf.PageCount;
}
pdf.PageMode = PdfPageMode.UseOutlines;
pdf.Save(destination);
}
}