asp vb save excel file in particular path - asp.net

refering to this link Creating an Excel Application from VB.Net
I want to save my excel file to this path:
C:\Users\asdfme\Documents
with the filename format [PROJ_DATE].xls example:PROJ_20140703.xls
here is my code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Call temporaryValue()
Dim appXL As Excel.Application
Dim wbXl As Excel.Workbook
Dim shXL As Excel.Worksheet
Dim raXL As Excel.Range
Dim strPathExcel As String
' Start Excel and get Application object.
appXL = CreateObject("Excel.Application")
appXL.Visible = True
' Add a new workbook.
wbXl = appXL.Workbooks.Add
shXL = wbXl.ActiveSheet
' Add table headers going cell by cell.
Dim heads() As String = {"", "MONo", "PostingDate", "DocDate", "SBU", "Operation", "Resource", "TimeType", "StartDate", "StartTime", "EndDate", "EndTime", "NoofResources", "Remarks", "Quantity", "Rejects"}
For head1 As Integer = 1 To 15
shXL.Cells(1, head1).Value = heads(head1)
Next
Dim body() As String = {"", txtmo.Text, PostingDate, DocDate, SBU, Operation, Session("user"), (ddltype.SelectedValue).ToUpper, lblsDate.Text, lblsTime.Text, lbleDate.Text, lbleTime.Text, no_ofres, lblrem.Text, txtgoods.Text, txtrejects.Text}
For body1 As Integer = 1 To 15
shXL.Cells(2, body1).Value = body(body1)
Next
appXL.Visible = True
appXL.UserControl = True
' Release object references.
wbXl.SaveAs(Filename:="C:\Users\asdfme\Documents\PROJ_20140703.xls")
raXL = Nothing
shXL = Nothing
wbXl = Nothing
appXL.Quit()
appXL = Nothing
Exit Sub
Err_Handler:
MsgBox(Err.Description, vbCritical, "Error: " & Err.Number)
End Sub
when i run this code,
it only create an excel file and ask me if i want to save the file.
what i want is whenever i run this, the file will save with the file name format (written above) in the path i declare.
Please help. thank you

Dim myXlsFileName As String = "PROJ_" & " " & Format(Now.Date, "yyyyddMM") & ""
wbXl.SaveAs(Filename:="C:\Documents and Settings\All Users\Desktop\" & myXlsFileName & ".xls")

Related

How can I stop Ionic zip from appending null to the end of a file

I have a VB.net (ASPX) which receives a file (data stream) from my application, and depending on switches will save the file as is or compress & encrypt it using ionic.zip. When a file is saved without encryption it is byte perfect. When the same file is compressed/encrypted and then decrypted/uncompressed there is an extra null (ascii(0)) character appended to the end of the decrypted file. This is generally not an issue, but MS Office products complain about corrupted files (then opens them fine).
The code I use is fairly straightforward and I cannot see any issues. I found nothing in my searches for this issue with ionic zip. Here is the code;
<%# Page Language="VB" validateRequest="false"%>
<%# Import Namespace="Ionic.Zip"%>
<%# Import Namespace="System.Web.HttpContext"%>
<script Runat="Server">
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim strToken As String = Request.QueryString("token")
Dim strSessionID As String = Request.QueryString("SessionID")
Dim strAlternateFileName As String = Request.QueryString("AlternateFileName")
Dim strDestinationFolder As String = Request.QueryString("DestinationFolder")
Dim strZipYN As String = Request.QueryString("ZipYN")
Dim strZipFileName As String = Request.QueryString("ZipFileName")
Dim strZipPassword As String = Request.QueryString("ZipPassword")
Dim fileName As String = System.IO.Path.GetFileName(Request.Files(0).FileName)
If IsNothing(Current.Session("token" & strSessionID)) _
Then
Current.Session("token") = strToken
Current.Session("token" & strSessionID) = Current.Session("token")
End If
If Len(strAlternateFileName) > 0 _
Then
fileName = strAlternateFileName
End If
If strZipYN <> "Y" _
Then
Request.Files(0).SaveAs(Server.MapPath(strDestinationFolder + "/") + fileName)
Else
Dim fileIn As HttpPostedFile
Dim objZipFile As ZipFile = New ZipFile
fileIn = Request.Files(0)
Dim intFileInLen = fileIn.ContentLength
Dim bytFielIn(intFileInLen) As Byte
Dim strmFileIn As System.IO.Stream
strmFileIn = fileIn.InputStream
strmFileIn.Read(bytFielIn, 0, intFileInLen)
If strZipPassword.Length > 0 _
Then
objZipFile.Password = strZipPassword
objZipFile.Encryption = EncryptionAlgorithm.WinZipAes256
End If
objZipFile.AddEntry(fileName, bytFielIn)
objZipFile.SaveSelfExtractor(Server.MapPath(strDestinationFolder + "/") + strZipFileName + ".exe", SelfExtractorFlavor.WinFormsApplication)
' objZipFile.SaveSelfExtractor(Server.MapPath(strDestinationFolder + "/") + strZipFileName + ".zip", SelfExtractorFlavor.WinFormsApplication)
objZipFile.Dispose()
objZipFile = Nothing
'Create a PW protected ZIP only for non windows computers.
objZipFile = New ZipFile
If strZipPassword.Length > 0 _
Then
objZipFile.Password = strZipPassword
objZipFile.Encryption = EncryptionAlgorithm.WinZipAes256
End If
objZipFile.AddEntry(fileName, bytFielIn)
objZipFile.Save(Server.MapPath(strDestinationFolder + "/") + strZipFileName + ".zip")
objZipFile.Dispose()
objZipFile = Nothing
End If
End Sub
</script>
Any ideas?
Edit:
I get the same results whether I extract the file from the ".exe" file, or the ".zip" file

end of statement expected in vb.net while storing value to the object?

Protected Sub Email_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim objExport As ClsItextSharp = New ClsItextSharp()
Dim strPath As String = ""
Dim objReport As Report = New Report()
objReport = (Telerik.Reporting.Report)RViewer.Report
strPath = CreatePDfwithPath1(objReport)
Dim docType As String = "EncounterNote"
Dim Imgop As ImageOperations = New ImageOperations()
Dim Path As String = Imgop.EncriptString(strpath)
Response.Redirect("../EMail/SendMail.aspx?send=M&Type=nothing&strpath=" + Path + "")
End Sub
end of statement expected in vb.net while storing value to the object? getting error on objReport = (Telerik.Reporting.Report)RViewer.Report.
What is this, C#?
objReport = (Telerik.Reporting.Report)RViewer.Report
I guess you want to cast it:
Dim objReport = CType(RViewer.Report, Telerik.Reporting.Report)

How Read .text file line by line and the stored in database in sql server

I have a module which upload report and then stored in database in sql server. Now I have come up with this code to read .txt file line by line.
Protected Sub ibtnTxtUpload_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim jsbldr As New StringBuilder
Try
If FileUpload1.HasFile Then
Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
If Extension = ".txt" Then
Dim Request_Val As String = ""
Dim sFileName As String = FileUpload1.FileName
'Read Line by Line
Using sRead As New StreamReader(FileUpload1.PostedFile.FileName)
sFileName = sRead.ReadToEnd
End Using
Dim sFileLines() As String = sFileName.Split(vbCrLf)
'Trim the line
Dim dt As New DataTable("XmlData")
dt.Columns.Add("Item", GetType(String))
dt.Columns.Add("Description", GetType(String))
dt.Columns.Add("Rev", GetType(String))
dt.Columns.Add("Locator", GetType(String))
dt.Columns.Add("UOM", GetType(String))
dt.Columns.Add("Quantity", GetType(Double))
Dim writer As New StringWriter
Dim sline As String
Dim i As Integer = 0
Dim lStart As Boolean = False
For Each sline In sFileLines
If sline.TrimStart.TrimEnd <> "" Then
If lStart = True Then
If sline.Substring(0, 10).TrimStart.TrimEnd <> "-------" Then
Dim newRow As DataRow = dt.NewRow
newRow("Item") = sline.Substring(0, 32).TrimStart.TrimEnd
newRow("Description") = sline.Substring(33, 53).TrimStart.TrimEnd
newRow("Rev") = sline.Substring(86, 3).TrimStart.TrimEnd
newRow("Locator") = sline.Substring(89, 26).TrimStart.TrimEnd
newRow("UOM") = sline.Substring(115, 3).TrimStart.TrimEnd
newRow("Quantity") = sline.Substring(124, 7).TrimStart.TrimEnd
dt.Rows.Add(newRow)
End If
End If
If sline.Substring(0, 32).TrimStart.TrimEnd = "Item" Then
lStart = True
End If
If sline.TrimStart.TrimEnd = "" Then
lStart = False
End If
End If
Next
'Execute SQL Stored Procedure
Using cn As New SqlConnection(cls.strConnString)
Using cmd As New SqlCommand()
With cmd
.CommandType = CommandType.StoredProcedure
.CommandText = "USP_XML_SOH_ACCOUNT_MAINT"
.Parameters.Add("#XMLdata", SqlDbType.Xml) : .Parameters("#XMLdata").Value = writer.ToString
.Parameters.Add("#USR_ID", SqlDbType.VarChar, 30) : .Parameters("#USR_ID").Value = cls.GetUserName
.Parameters.Add("#FILE_NAME", SqlDbType.VarChar, 255) : .Parameters("#FILE_NAME").Value = sFileName
.Parameters.Add("#RET_VAL", SqlDbType.VarChar, 255)
.Parameters("#RET_VAL").Direction = ParameterDirection.Output
.Connection = cn
cn.Open()
.ExecuteNonQuery()
Request_Val = .Parameters("#RET_VAL").Value.ToString
End With
End Using
End Using
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Javascript", "<script>$(document).ready(function(){$('#grid-div').height(250);$.blockUI({message: 'Updating data...',css: {border: 'none',padding: '15px', width: '15%', left: '40%',backgroundColor: '#000','-webkit-border-radius': '10px','-moz-border-radius': '10px',opacity: .5,color: '#fff'}});setTimeout($.unblockUI, 2000); " & _
" $('#dialog-message').html('<table style=""border-style:hidden;""><tr><td style=""padding:5px;""> <img src=""images/gridview/check_circle_64x64.png""/></td><td>" & Request_Val.ToString & "</td></tr></table>');" & _
"$('div#dialog-message').dialog ({ my: 'center', at: 'center', of: window}).prev ().find ('.ui-dialog-titlebar-close').hide(); " & _
"var varCounter = 0; var varName = function(){ if(varCounter < 1){ varCounter++; $('#dialog-message').dialog('open'); } else {clearInterval(varName);}};setInterval(varName, 2000);}); </script>")
Else
jsbldr.Append("<script>")
jsbldr.Append("$(document).ready(function(){")
jsbldr.Append("$('div#dialog-message').dialog ({ my: 'center', at: 'center', of: window}).prev ().find ('.ui-dialog-titlebar-close').hide();")
jsbldr.Append("$('#dialog-message').html('<table style=""border-style:hidden;""><tr><td style=""padding:5px;""> <img src=""images/gridview/exclamation_circle_64x64.png""/></td><td>Invalid file format, please use .xlsx excel file extention.</td></tr></table>');")
jsbldr.Append("$('#dialog-message').dialog('open');")
jsbldr.Append("});")
jsbldr.Append("</script>")
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Javascript", jsbldr.ToString)
End If
End If
Catch ex As Exception
jsbldr.Append("<script>")
jsbldr.Append("$(document).ready(function(){")
jsbldr.Append("$('div#dialog-message').dialog ({ my: 'center', at: 'center', of: window}).prev ().find ('.ui-dialog-titlebar-close').hide();")
jsbldr.Append("$('#dialog-message').html('<table style=""border-style:hidden;""><tr><td style=""padding:5px;""> <img src=""images/gridview/exclamation_circle_64x64.png""/></td><td>Uploading SOH Account file template encounter error, please check the file.</td></tr></table>');")
jsbldr.Append("$('#dialog-message').dialog('open');")
jsbldr.Append("});")
jsbldr.Append("</script>")
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Javascript", jsbldr.ToString)
End Try
End Sub
Here's the actual text file, in every end of the record there is an end symbol, I'm trying to put here but it can't capture.
Item Description Rev Locator UOM Quantity
------------------------------------------------------------------------------- --- ------------------------- --- ------------
604K23660 KIT-FDR HCF MSI ANG.2.0.0 PC 1.00
604K23670 KIT FEEDER TM ANG.2.0.0 PC 3.00
604K26021 LEN ASSY ANG.2.0.0 PC 1.00
CT200541 AP/DCC4400/4300/3300/2200 Cartridge Toner ANG.2.0.0 Unt 3.00
(Magenta)
CT200542 AP/DCC4400/4300/3300/2200 Cartridge Toner (Yellow) ANG.2.0.0 Unt 6.00
Subinventory: NEI-OLO Description: Non-Equipment Inventory of Olongapo
Item Description Rev Locator UOM Quantity
------------------------------------------------------------------------------- --- ------------------------- --- ------------
CT350769 DC-III 3007/2007 Drum Cartridge Standard PC 7.00
CT350851 AP/DC-IV C5570/4470/3370/3371/2270 Long Life Drum PC 2.00
Cartridge (1 piece)
I put some condition in my For Each for the file. Now the condition read each line where to start reading and where to end and then add each row in my datatable, it loop until lStart = FALSE but I have an error on my condition if the record reached the ending symbol lSTart = False and then will loop again to find the "Item".
For Each sline In sFileLines
If sline.TrimStart.TrimEnd <> "" Then
If lStart = True Then
If sline.Substring(0, 10).TrimStart.TrimEnd <> "-------" Then
Dim newRow As DataRow = dt.NewRow
newRow("Item") = sline.Substring(0, 32).TrimStart.TrimEnd
newRow("Description") = sline.Substring(33, 53).TrimStart.TrimEnd
newRow("Rev") = sline.Substring(86, 3).TrimStart.TrimEnd
newRow("Locator") = sline.Substring(89, 26).TrimStart.TrimEnd
newRow("UOM") = sline.Substring(115, 3).TrimStart.TrimEnd
newRow("Quantity") = sline.Substring(124, 7).TrimStart.TrimEnd
dt.Rows.Add(newRow)
End If
End If
If sline.Substring(0, 32).TrimStart.TrimEnd = "Item" Then
lStart = True
End If
If sline.TrimStart.TrimEnd = "" Then
lStart = False
End If
Here's my condition on the ending symbol, apparently the symbol can't capture here,but on visual studio it can.
If sline.TrimStart.TrimEnd = "" Then
lStart = False
End If
After reading all the data, I need an XMLData to write this on the database in sql server. So I have a stored procedure for this. It is not working yet because the error on my For Each Condition.
I appreciate the suggestion and help, feel free to right my codes. Thanks
I picked to put them in a list but you could use an array. I don't need to show you how to insert values inside excel as you seem to know already. Skip the 2 first line or insert them as headers inside your excel file. concept is the same.
Dim xstr As String = "007K88431 GEAR ASSY-20/46 ANG.2.0.0 PC 1.00"
Dim xline As New List(Of String)
xline.Add(Strings.Mid(xstr, 1, 30).Trim)
xline.Add(Strings.Mid(xstr, 31, 56).Trim)
xline.Add(Strings.Mid(xstr, 87, 26).Trim)
xline.Add(Strings.Mid(xstr, 113, 4).Trim)
xline.Add(Strings.Mid(xstr, 117).Trim)
That seems like a lot of surpfluous code for uploading a file! To load a Text file or a CSV, which is the same thing, run the following script.
BULK INSERT TmpStList FROM 'c:\TxtFile1.txt' WITH (FIELDTERMINATOR = '","')

How I read XLMS file row by row after a condition?

I have a problem with a XLSM Excel of which I want to get some data by condition.
Excel image
In the picture I have "Name", and "Status", if the status is "Completed" I want to take their value on "Time Assembly -> Post Assembly" where the value is "1.11". For each value of "Time Assembly" in the end I want to do media.
my code:
If FileUpload1.HasFile = False Then
Exit Sub
Else
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
'Dim FolderPath As String = ConfigurationManager.AppSettings("Upload")
Dim FilePath As String = Server.MapPath("~") & "\Upload\" & FileName
FileUpload1.SaveAs(FilePath)
Dim existingFile = New FileInfo(FilePath)
Dim pack As ExcelPackage = New ExcelPackage(existingFile)
Dim workBook As ExcelWorkbook = pack.Workbook
If workBook.Worksheets.Count > 0 Then
Dim currentWorksheet As ExcelWorksheet = workBook.Worksheets.First()
End If
End If
In that "if" I want to read Excel row by row, after that condition.
Thanks a lot!
Try to find the last row in the sheet and use for loop to iterate the condition
Sub test()
Dim lastRow As Long
Dim workBook As workBook
workBook = ThisWorkbook
lastRow = workBook.ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
For i = 3 To lastRow
'for checking value in the 4 column(D column)
If (workBook.ActiveSheet.Cells(i, 4).Value) = "completed" Then
workBook.ActiveSheet.Cells(i, 6).Value = "xx"
End If
'for adding value in the 6 column
Next
End Sub

comparing two ms access backend databases of an asp.net web application

at our office we take daily backup of ASP.net application ms access backend
for the next few days we need to evaluate the changes made to records in the database tables
at the end of each day i want to compare 2 access databases first database is the backup of yesterday and second database is the backup of today
i thought of the following algorithm, please read carefully and tell me how to proceed to compare the datatables / gridviews
i need to display th rows / cells containing the differences / updates / deleted data
Imports System.Data
Imports System.Data.OleDb
Partial Class MoKoTrack
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myDB = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|database.mdb;Persist Security Info=True")
Session("CurrentDB") = myDB
myDB.open()
Dim mytables = myDB.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {})
Dim CurrentTable As String
Dim ee As Integer = mytables.Rows.Count
Dim OriginalTables(ee) As String
Dim BackupTables(ee) As String
Dim X As Integer = 0
For i = 1 To mytables.Rows.Count
CurrentTable = mytables.Rows(i - 1).Item(2).ToString
If mytables.Rows(i - 1).Item(3).ToString = "TABLE" Or mytables.Rows(i - 1).Item(3).ToString = "VIEW" Then
If CurrentTable.Contains("Backup") Then
BackupTables(X) = CurrentTable
Else
OriginalTables(X) = CurrentTable
End If
X = X + 1
End If
Next i
For i = 0 To BackupTables.Count - 1
If Not BackupTables(i) = "" Then
CompareTable(BackupTables(i))
End If
Next
myDB.Close()
End Sub
Sub CompareTable(ByVal BackupTableName As String)
Dim OriginalTable As New DataTable
Dim BackupTable As New DataTable
Dim ModificationsTable As New DataTable
Dim myDB = Session("CurrentDB")
Dim FinalSQLString = "SELECT * FROM [" + BackupTableName + "]"
Dim myDBCommand = New OleDbCommand(FinalSQLString, myDB)
'Generate a temporary reader to get the number of cases
Dim myReader As IDataReader = myDBCommand.ExecuteReader()
'Dim myColumns = myReader.GetSchemaTable
'For I = 1 To myColumns.Rows.Count
' OriginalTable.Columns.Add(myColumns.Rows(I - 1).Item(0).ToString())
'Next I
BackupTable.Load(myReader)
Dim OriginalTableName = Left(BackupTableName, Len(BackupTableName) - 6)
Dim FinalSQLString2 = "SELECT * FROM [" + BackupTableName + "]"
Dim myDBCommand2 = New OleDbCommand(FinalSQLString, myDB)
'Generate a temporary reader to get the number of cases
Dim myReader2 As IDataReader = myDBCommand.ExecuteReader()
OriginalTable.Load(myReader2)
'Dim myGrid As New GridView
'myGrid.DataSource = OriginalTable
'myGrid.DataBind()
'Me.form1.Controls.Add(myGrid)
'Dim myGrid2 As New GridView
'myGrid2.DataSource = BackupTable
'myGrid2.DataBind()
'Me.form1.Controls.Add(myGrid2)
For i = 0 To OriginalTable.Rows.Count - 1
For t = 0 To OriginalTable.Columns.Count - 1
Next
Next
End Sub
End Class
i am using the following VBA code to rename backup database tables into "tablebackup"
Private Sub Command0_Click()
Dim tdf As TableDef
For Each tdf In CurrentDb.TableDefs
If Left(tdf.Name, 4) <> "MSys" Then
tdf.Name = tdf.Name & "backup"
End If
Next
End Sub
Can you add a ModifiedOn field for each table and extract the rows that have been modified since the last day. You can compare the modified ones (the ones that exist in the backup) and write out all new ones (the ones that don't).

Resources