ASP.NET to Excel export - reference file and open save as dialog? - asp.net

I have this code:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Here we go. All the data in the form to an Excel sheet. Cross your fingers...
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel- this isn't really what I need though, I need it to open a template and populate it.
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open("C:\Users\jagtars\Desktop\HI Resources\HI.xlsx")
'Add data to cells of the first worksheet in the new workbook
oSheet = oBook.Worksheets(1)
oSheet.Range("H5").Value = CustomerName.Text
oSheet.Range("K5").Value = dropdown_serverVirtualisation.Value
oSheet.Range("L5").Value = dropdown_desktopVirtualisation.Value
oSheet.Range("M5").Value = dropdown_oracle.Value
oSheet.Range("N5").Value = dropdown_sqlServer.Value
'etc....
'Save the Workbook and Quit Excel
oBook.SaveAs("C:\Users\jagtars\Desktop\HI.xlsx")
MessageBox.Text = "Exported!"
MessageBox.Focus()
oExcel.Quit()
End Sub
This code grabs a file from a folder in my desktop and then edits it and saves it as a new file 'HI' in my Desktop.
Instead I would like to place this file in my project folder and then reference it and after that the user should get the option to where they want to save the new modified file.
What do I need to modify in my code to achieve this?
Thanks All.

You should use HttpResponse.WriteFile method. Browser will automatically show dialog to user. To get path inside you project you could use HttpServerUtility.MapPath

Related

Overload File Function VB.NET

I am trying to create an onclick function through ASP front end to check if a file exists, if not create it and write textbox text to it, currently getting an error on the below code saying that I cannot overload the file function, is there a better way of doing this?
UPDATE
The issue is the file is still open when trying to write to it which is throwing the error.
Please see below code:
Protected Sub Create_Click(sender As Object, e As EventArgs)
Dim txtFile As String = "E:Documents\Visual Studio 2013\Projects\SomeProject\Templates\" & FileName.Text & ".txt"
If File.Exists(txtFile) Then
Response.Write("A file of that name already exists.")
Else
File.Create(txtFile)
File.WriteAllText(eTemplate.Text)
End If
End Sub
I have also tried:
If File.Exists(txtFile) Then
Response.Write("A file of that name already exists.")
Else
System.IO.File.Create(txtFile)
Dim sw As New StreamWriter(txtFile, True)
sw.Write(eTemplate.Text)
sw.Close()
End If
You're right on the money, it is because it needs to be closed first.
I created a file stream instance first, created the file, closed it and then wrote to it. Put the below code in yours or write it out, but remember to correct the file path.
Protected Sub Create_Click(sender As Object, e As EventArgs)
Dim txtFile As String = "E:\wherever\" & FileName.Text & ".txt"
If System.IO.File.Exists(txtFile) Then
Dim message As String = "A file by this name already exists, choose another or update the existing file."
Else
Dim fs As FileStream = File.Create(txtFile)
fs.Close()
Dim sw As New StreamWriter(txtFile, True)
sw.Write(eTemplate.Text)
sw.Close()
End If
End Sub

Error happens during file open in asp.net on wep page?

I try to open the file and update content in the file, it gets sum error like this.
My code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Request.QueryString("log") = "no" Then
pinfo.Text = "Invalid Username / Password"
End If
Session.Clear()
Dim FileWriter As StreamWriter
Dim FileReader As StreamReader
Dim Countstr As String
FileReader = File.OpenText("/dmkg/Counter.txt")
Countstr = FileReader.ReadLine
FileReader.Close()
Countstr = Countstr + 700
FileWriter = File.CreateText("/dmkg/Counter.txt")
FileWriter.WriteLine(Countstr)
FileWriter.Close()
End Sub
Check the code and tell me where I am going wrong.
You have to Pass Correct PATH in OpenText Method not File Name
File.OpenText()
Eg:
Dim path As String = "c:\temp\MyTest.txt"
FileReader = File.OpenText(path)
So Make sure your file path is correct.
If it's stored in server then you need to use Server.Mappath()
FileReader = File.OpenText(Server.MapPath("/dmkg/Counter.txt"))
Server.MapPath
To Enable a Access
To grant ASP.NET write access to a path,
right-click the file in Explorer,
choose "Properties" and select the Security tab.
Click "Add" to add the appropriate user or group (typically
{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6).
Highlight the needed account, and check the boxes for the desired
access.

save excel using EPPlus

could someone help me with this error??
I tried to save excel file using EPPlus
[IOException: The process cannot access the file 'C:\Users\Julian\Downloads\EmployeeMaster.xls' because it is being used by another process.]
here is my code :
Dim conn As New ConnectionVB
Dim newfile As FileInfo = NewFileInfo("C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls")
Using p As ExcelPackage = New ExcelPackage(newfile)
SetWorkBookProperties(p)
conn.connect()
Dim ws As ExcelWorksheet = CreateSheet(p, "EmnployeeMaster")
Dim dt As New DataTable
Dim connString As String
connString = "Select * from EmployeeMaster"
dt = conn.openDataTable(connString)
Dim rowIndex As Integer
rowIndex = 2
CreateHeader(ws, rowIndex, dt)
CreateData(ws, rowIndex, dt)
Dim bin As Byte()
bin = p.GetAsByteArray()
Dim path As String
path = "C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls"
File.Delete("C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls")
Dim stream As Stream = File.Create(path)
File.WriteAllBytes(path, bin) <- I got the error here
Start(path)
stream.Close()
End Using
Appriciate all help/advice with this error
Regards Siekh
As from your Error shows: EmployeeMaster.xls file is being used by another process.
Your code DryRun:
In your EmployeeMaster.xls file you make another new sheet name as EmnployeeMaster and then you create Header, and Data in this sheet.
problem arise when you write to file. you have to just save WorkSheet by doing .
because just open your .xls file with the help of EPPlusPackage and then by code Add your custom sheet in .xls file and just save.
p.Save(); // you need to save this temporary sheet.
Problems may be:
EPPLUS cannot open xls files, only xlsx files.
Why you delete File.
solution: you can rename and then move.
EPPlus hold your file when you instantiate object for ExcelPackage(with the same Path)
Two Problems:
EPPlus does not support xls files.
For debugging why the file is used, I recommend using SysInternal's "process explorer", you can find it here.

How to create file on server with special privileges on Asp .net using visual basic?

One of the client requirements is that the server generate files and store them on a special folder. This files created can not be modified by users or deleted.
So the only way I thought is to generate this files with elevated privileges so a normal user can't delete or modify them.
But the question is how can I generate a file with this privileges that normal users can interact with this files... only download from server.
I use this code to generate the file... But I don't know how to configure it for elevated privileges.
This is the button which generate the file and allow to download it:
Protected Sub ibtGenerar_OnClick(ByVal sender As Object, ByVal e As ImageClickEventArgs)
oArchivoTelecredito.NombreArchivo = txtNombreArchivo.Text
oArchivoTelecredito.SesionDetalleArchivosTelecredito = New List(Of DetalleArchivoTelecreditoBE)
Dim oArchivoTelecreditoSL As New ArchivoTelecreditoSL
Response.AddHeader("Content-disposition", "attachment;filename=" & oArchivoTelecredito.NombreArchivo & ".txt")
Response.ContentType = "application/octet-stream"
Response.BinaryWrite(oArchivoTelecreditoSL.GeneraArchivoTelecredito(oArchivoTelecredito, Server.MapPath(oArchivoTelecredito.NombreArchivo)))
Response.End()
End Sub
This is the function which create the file on server:
Public Function GeneraArchivoTelecredito(ByVal telecredito As ArchivoTelecreditoBE, ByVal ruta As String) As Byte()
Dim lineas As Integer = telecredito.SesionDetalleArchivosTelecredito.Count + 1
Dim registro(0 To lineas) As String
registro(0) = Me.ObtenerCabeceraArchivoTelecredito(telecredito)
Dim archivo = ruta & ".txt"
Using escritor As New StreamWriter(archivo)
For index = 0 To lineas
escritor.WriteLine(registro(index))
Next
escritor.Close()
End Using
Dim lector As FileStream
lector = File.Open(archivo, FileMode.Open)
Dim bytes(lector.Length) As Byte
lector.Read(bytes, 0, lector.Length)
lector.Close()
Return bytes
End Function
If you want to set the file to be read-only then you can use
File.SetAttributes("PathToFile", FileAttributes.ReadOnly).
You could also set the permissions on the directory itself instead of the individual files - see this post: https://serverfault.com/questions/3878/is-there-a-way-to-prevent-a-file-from-being-deleted

a ButtonField within DataGrid calling Vb.net as Javascript.... for streaming PDF?

I just noticed it last night,
Anyway, let's get to the interesting case here.
I have a ButtonField within DataGrid, and if you notice it here...
The Interface of that ButtonField is looks like a LINK.
But if we hover on it, it appeared as Javascript's call.
Here is the Image ScreenShot
Ya, that's the 1st case.
IT IS a javascript's call.
I didnt notice about it lately. (hehehe).
Then, if we click on that... it would call the createPDF() function. The function behind the scene (which I'm using VB.net) is to execute these code;
Protected Sub createPDF()
Dim document As New Document()
Dim mem As LengthFixingStream = New LengthFixingStream()
' instantiate a iTextSharp.text.pdf.Document
'Dim mem As New MemoryStream()
' PDF data will be written here
PdfWriter.GetInstance(document, mem)
' tie a PdfWriter instance to the stream
document.Open()
Dim titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD)
document.Add(New Paragraph("Northwind Traders Receipt", titleFont))
document.Close()
' automatically closes the attached MemoryStream
Dim docData As Byte() = mem.GetBuffer()
' get the generated PDF as raw data
' write the document data to response stream and set appropriate headers:
Response.AppendHeader("Content-Disposition", "attachment; filename=testdoc.pdf")
Response.ContentType = "application/pdf"
Response.BinaryWrite(docData)
Response.[End]()
End Sub
But somehow... this of course would not deliver the PDF into the browser.
BEcause It's called by Javascript, nor the direct as Hyperlink (normally).
Thus, I'm wondering could we get the ASP.net Call new Window,
and then redirect the createPDF() result into it?
Correct me if i'm wrong...
Here is just some mockup so you get the idea. I haven't tested this. Basically you will have to put the above code in a new page...say "receipt.aspx" and execute it on the load event...you will need to setup an id parameter...if data is being pulled from the db to generate the pdf.
on the button click add the following
Dim sb As New System.Text.StringBuilder()
sb.Append("<script language='javascript'>")
sb.Append("window.open('receipt.aspx.htm?id=123'', 'Receipt',")
sb.Append("'width=800, height=800, menubar=yes, resizable=no');<")
sb.Append("/script>")
Dim t As Type = Me.GetType()
If Not ClientScript.IsStartUpScriptRegistered(t, "PopupScript") Then
ClientScript.RegisterStartUpScript(t, "PopupScript", sb.ToString())
End If
Notice the "id=123" querystring value I am passing to receipt.aspx?
You can then call that in the receipt.aspx page like this
Dim id as String = Request.QueryString("id")
CreatePDF(id)
...shoot! Just realized you are using a Grid...the principle remains the same, just wireup the buttons on RowDataBound event.
Protected Sub GridView_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim Id As String = DirectCast(e.Row.Cells(0).FindControl("quotationid"), Label).Text
Dim myButton As New Button
myButton = DirectCast(e.Row.Cells(4).FindControl("btnViewReceipt"), Button)
myButton.Attributes.Add("OnClick", "window.open('receipt.aspx?id=" + id + "','Receipt','scrollbars=yes','width=800,height=800')")
End If
End Sub

Resources