473,382 Members | 1,424 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

Save an Excel from to client using Asp.Net

Jae
I'm writing a web application that exports and imports excel files.
The application gets a list of users and their info and displays it in
a datagrid .The user then selects to save the file as a tab delimited
file or an excel file. The application then saves the file in the
correct format.
The flip side is for the user to import/upload the file to the server
The application must be able to import the excel file and read the
contents.
I have searched here and kB 316934 How to Use Ado.Net to Retrieve and
Modify Records. That example assumes permissions on the client
machinme which I will not have

Here is a code snippet of the excel export :
' Set the content type to Excel.
Response.ContentType = "application/vnd.ms-excel"
' Remove the charset from the Content-Type header.
Response.Charset = ""
' Turn off the view state.
Me.EnableViewState = False

Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
' Get the HTML for the control.
DataGrid1.RenderControl(hw)
' Write the HTML back to the browser.
Dim strFileName As String = "Roster_Export_" &
m_objCourse.CourseKey.ToString.Replace("/", "_")

Response.Clear()
Response.Buffer = True
Response.Expires = 0
' Change the HTTP header to reflect that an image is being passed.
strFileName = strFileName & ".xls"
Response.AddHeader("Content-Disposition", "attachment; filename=" &
strFileName)

Response.Flush()
Response.Write(tw.ToString())
' End the response.
Response.End()
Here is my import code :

Dim _files As HttpFileCollection = HttpContext.Current.Request.Files
Dim _message As System.Text.StringBuilder = New
System.Text.StringBuilder("File Uploaded:<br>")
Dim sConnectionString As String
Try
Dim _iFile As Integer
For _iFile = 0 To _files.Count - 1
Dim _postedFile As HttpPostedFile = _files(_iFile)
Dim _fileName As String
If _postedFile.FileName <> "" Then
_fileName = System.IO.Path.GetFullPath(_postedFile.FileName)
' Create connection string variable. Modify the "Data Source"
parameter as
' appropriate for your environment.
'Dim sConnectionString As String = BuildConnectionString(_fileName)

sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
sConnectionString += "Data Source=" & _fileName & ";"
sConnectionString += "Extended Properties=""Excel 8.0;HDR=YES;"""
' Create the connection object by using the preceding connection
string.
Dim objConn As New OleDbConnection(sConnectionString)
' Open connection with the database.
objConn.Open()

' The code to follow uses a SQL SELECT command to display the data
from the worksheet.
' Create new OleDbCommand to return data from worksheet.
'Dim objCmdSelect As New OleDbCommand("SELECT * FROM [Week2$] ",
objConn)
Dim objCmdSelect As New OleDbCommand("SELECT * FROM [RosterExport$]
", objConn)
' Create new OleDbDataAdapter that is used to build a DataSet
' based on the preceding SQL SELECT statement.

Dim objAdapter1 As New OleDbDataAdapter()
' Pass the Select command to the adapter.

objAdapter1.SelectCommand = objCmdSelect
' Create new DataSet to hold information from the worksheet.

Dim objDataset1 As New DataSet()
' Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData")

This will save the file but requires the user to save the file as an
excel file. A step I do not wish to take. A test of the application is
to do an export and then do an import (same file) with no hiccup.
Currently the file has to be opened and saved to an actual excel for
it is really an html file with an xls extension.

Any help would be greatly appreciated

JAE
Nov 17 '05 #1
4 4501
This maybe helpful:

Export to Excel

http://www.aspnetpro.com/features/20...200310so_f.asp

Requires an asp.netPRO subscription.

Greg
"Jae" <ak*********@earthlink.net> wrote in message
news:22**************************@posting.google.c om...
I'm writing a web application that exports and imports excel files.
The application gets a list of users and their info and displays it in
a datagrid .The user then selects to save the file as a tab delimited
file or an excel file. The application then saves the file in the
correct format.
The flip side is for the user to import/upload the file to the server
The application must be able to import the excel file and read the
contents.
I have searched here and kB 316934 How to Use Ado.Net to Retrieve and
Modify Records. That example assumes permissions on the client
machinme which I will not have

Here is a code snippet of the excel export :
' Set the content type to Excel.
Response.ContentType = "application/vnd.ms-excel"
' Remove the charset from the Content-Type header.
Response.Charset = ""
' Turn off the view state.
Me.EnableViewState = False

Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
' Get the HTML for the control.
DataGrid1.RenderControl(hw)
' Write the HTML back to the browser.
Dim strFileName As String = "Roster_Export_" &
m_objCourse.CourseKey.ToString.Replace("/", "_")

Response.Clear()
Response.Buffer = True
Response.Expires = 0
' Change the HTTP header to reflect that an image is being passed.
strFileName = strFileName & ".xls"
Response.AddHeader("Content-Disposition", "attachment; filename=" &
strFileName)

Response.Flush()
Response.Write(tw.ToString())
' End the response.
Response.End()
Here is my import code :

Dim _files As HttpFileCollection = HttpContext.Current.Request.Files
Dim _message As System.Text.StringBuilder = New
System.Text.StringBuilder("File Uploaded:<br>")
Dim sConnectionString As String
Try
Dim _iFile As Integer
For _iFile = 0 To _files.Count - 1
Dim _postedFile As HttpPostedFile = _files(_iFile)
Dim _fileName As String
If _postedFile.FileName <> "" Then
_fileName = System.IO.Path.GetFullPath(_postedFile.FileName)
' Create connection string variable. Modify the "Data Source"
parameter as
' appropriate for your environment.
'Dim sConnectionString As String = BuildConnectionString(_fileName)

sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
sConnectionString += "Data Source=" & _fileName & ";"
sConnectionString += "Extended Properties=""Excel 8.0;HDR=YES;"""
' Create the connection object by using the preceding connection
string.
Dim objConn As New OleDbConnection(sConnectionString)
' Open connection with the database.
objConn.Open()

' The code to follow uses a SQL SELECT command to display the data
from the worksheet.
' Create new OleDbCommand to return data from worksheet.
'Dim objCmdSelect As New OleDbCommand("SELECT * FROM [Week2$] ",
objConn)
Dim objCmdSelect As New OleDbCommand("SELECT * FROM [RosterExport$]
", objConn)
' Create new OleDbDataAdapter that is used to build a DataSet
' based on the preceding SQL SELECT statement.

Dim objAdapter1 As New OleDbDataAdapter()
' Pass the Select command to the adapter.

objAdapter1.SelectCommand = objCmdSelect
' Create new DataSet to hold information from the worksheet.

Dim objDataset1 As New DataSet()
' Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData")

This will save the file but requires the user to save the file as an
excel file. A step I do not wish to take. A test of the application is
to do an export and then do an import (same file) with no hiccup.
Currently the file has to be opened and saved to an actual excel for
it is really an html file with an xls extension.

Any help would be greatly appreciated

JAE

Nov 17 '05 #2
A method I use is to transform the XML into HTML, save it to a file with a
..xls extension, then write the file to the browser.

Excel does a great job of displaying simple HTML. And you trick it into
displaying HTML in Excel when you save the file with an excel extension

"Greg Burns" <gr********@hotmail.com> wrote in message
news:e$**************@TK2MSFTNGP09.phx.gbl...
This maybe helpful:

Export to Excel

http://www.aspnetpro.com/features/20...200310so_f.asp

Requires an asp.netPRO subscription.

Greg
"Jae" <ak*********@earthlink.net> wrote in message
news:22**************************@posting.google.c om...
I'm writing a web application that exports and imports excel files.
The application gets a list of users and their info and displays it in
a datagrid .The user then selects to save the file as a tab delimited
file or an excel file. The application then saves the file in the
correct format.
The flip side is for the user to import/upload the file to the server
The application must be able to import the excel file and read the
contents.
I have searched here and kB 316934 How to Use Ado.Net to Retrieve and
Modify Records. That example assumes permissions on the client
machinme which I will not have

Here is a code snippet of the excel export :
' Set the content type to Excel.
Response.ContentType = "application/vnd.ms-excel"
' Remove the charset from the Content-Type header.
Response.Charset = ""
' Turn off the view state.
Me.EnableViewState = False

Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
' Get the HTML for the control.
DataGrid1.RenderControl(hw)
' Write the HTML back to the browser.
Dim strFileName As String = "Roster_Export_" &
m_objCourse.CourseKey.ToString.Replace("/", "_")

Response.Clear()
Response.Buffer = True
Response.Expires = 0
' Change the HTTP header to reflect that an image is being passed.
strFileName = strFileName & ".xls"
Response.AddHeader("Content-Disposition", "attachment; filename=" &
strFileName)

Response.Flush()
Response.Write(tw.ToString())
' End the response.
Response.End()
Here is my import code :

Dim _files As HttpFileCollection = HttpContext.Current.Request.Files
Dim _message As System.Text.StringBuilder = New
System.Text.StringBuilder("File Uploaded:<br>")
Dim sConnectionString As String
Try
Dim _iFile As Integer
For _iFile = 0 To _files.Count - 1
Dim _postedFile As HttpPostedFile = _files(_iFile)
Dim _fileName As String
If _postedFile.FileName <> "" Then
_fileName = System.IO.Path.GetFullPath(_postedFile.FileName)
' Create connection string variable. Modify the "Data Source"
parameter as
' appropriate for your environment.
'Dim sConnectionString As String = BuildConnectionString(_fileName)

sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
sConnectionString += "Data Source=" & _fileName & ";"
sConnectionString += "Extended Properties=""Excel 8.0;HDR=YES;"""
' Create the connection object by using the preceding connection
string.
Dim objConn As New OleDbConnection(sConnectionString)
' Open connection with the database.
objConn.Open()

' The code to follow uses a SQL SELECT command to display the data
from the worksheet.
' Create new OleDbCommand to return data from worksheet.
'Dim objCmdSelect As New OleDbCommand("SELECT * FROM [Week2$] ",
objConn)
Dim objCmdSelect As New OleDbCommand("SELECT * FROM [RosterExport$]
", objConn)
' Create new OleDbDataAdapter that is used to build a DataSet
' based on the preceding SQL SELECT statement.

Dim objAdapter1 As New OleDbDataAdapter()
' Pass the Select command to the adapter.

objAdapter1.SelectCommand = objCmdSelect
' Create new DataSet to hold information from the worksheet.

Dim objDataset1 As New DataSet()
' Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData")

This will save the file but requires the user to save the file as an
excel file. A step I do not wish to take. A test of the application is
to do an export and then do an import (same file) with no hiccup.
Currently the file has to be opened and saved to an actual excel for
it is really an html file with an xls extension.

Any help would be greatly appreciated

JAE


Nov 17 '05 #3
Here you go, there's a lot excluded for brevity. But all you need is in here

// get back the search results
DataSet dsReport = ExecuteReportReturnDataSet();
// write them out to disk
string exportPath = Facade.Export.ExportDataSet(
dsReport,
Session["UserLogin"].ToString(),
ConfigurationSettings.AppSettings["ApplicationPath"].ToString() +
ConfigurationSettings.AppSettings["ReportPath"].ToString(),
ConfigurationSettings.AppSettings["ApplicationPath"].ToString() +
@"xsl\gb_report_flash.xsl",
Convert.ToInt32(cUIHelper.ExportFormat.ExportXls). ToString());

// Write the Report to the Browser
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/vnd.ms-excel";
Response.WriteFile(exportPath);
Response.Flush();
Response.Close();

System.IO.File.Delete(exportPath);

#region ExportDataSet UserName, FilePath, XslPath, ExportFormatChoice
public static string ExportDataSet(
DataSet SearchResults,
string UserName,
string FilePath,
string XslPath,
string ExportFormatChoice)
{
string exportPath = "";

switch ((ExportFormat)Convert.ToInt32(ExportFormatChoice) )
{
case (ExportFormat.ExportXls):
exportPath = FilePath + UserName + "_SearchResults.xls";
break;
case (ExportFormat.ExportHtml):
exportPath = FilePath + UserName + "_SearchResults.html";
break;
}

// Create a FileStream to write with
System.IO.FileStream fs = new System.IO.FileStream(
exportPath, System.IO.FileMode.Create);
// Create an XmlTextWriter for the FileStream
System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(
fs, System.Text.Encoding.Unicode);
try
{
XmlDataDocument xmlDoc = new XmlDataDocument(SearchResults);
System.Xml.Xsl.XslTransform xslTran = new System.Xml.Xsl.XslTransform();
xslTran.Load(XslPath);
xslTran.Transform(xmlDoc, null, xtw);
xtw.Close();
return exportPath;
}
catch (Exception ex)
{
xtw.Close();
System.IO.File.Delete(exportPath);
ExceptionManager.Publish(ex);
throw(ex);
}
}
#endregion
Nov 17 '05 #4
Jae
"George Durzi" <gdurzi@nospam_hotmail.com> wrote in message news:<eH**************@tk2msftngp13.phx.gbl>...
Here you go, there's a lot excluded for brevity. But all you need is in here


Thanks George I tried that code snippet but was unable to get the
importer to understand the excel file. I'm not sure why jet is having
a problem but I still get the table is not in a recognized format
error.
Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Kelmen Wong | last post by:
Greeting, We have an ASP.NET app, developed using c#. There's a feature which a page (UserControl) when postback, it will download a PDF/Excel file through typical Response and Content Header...
2
by: PB | last post by:
I need to enable users to download data in either an Excel file or an Access database (MDB file). The data they need exists in a SQL Server database: the XLS or MDB file does not actually exist...
5
by: Patrick | last post by:
Following on from the excellent example at http://www.c-sharpcorner.com/Code/2003/Sept/ExportASPNetDataGridToExcel.asp on how to save a data-grid to excel file, how can I extend the example such...
6
by: Michael Groeger | last post by:
Hi, I have an aspx page which generates an excel document and transfers it to the browser as attachment. Normally, once the document is transferred the open save dialog prompts to open or save...
2
by: iloveprincess | last post by:
Hi, I'm developing windows application using VB.Net 2005. I would like to send 'save' message using 'SendMessage' API to the excel appication. I've already got a handle of the excel window with...
3
by: S_K | last post by:
Hi, I have a problem when I try to save a .CSV file from an ASP.NET web page and the client has Excel open already. The symptoms are: 1) The web page is currently displaying the Excel...
6
scubak1w1
by: scubak1w1 | last post by:
Hello, I have been Googling for a bit now as to how to let the user save the current page via a 'clickable icon' to an HTML file (i.e., on the client side.) That is, I am presenting a lot of...
3
by: =?Utf-8?B?YzY3NjIyOA==?= | last post by:
Hi all, I have a question for you. I have a .csv file which has many lines of data. Each line has many data fields which are delimited by ",". Now I need to extract part of data from this...
3
by: evenlater | last post by:
I have an Access application on a terminal server. Sometimes my users need to export reports to pdf, rtf or xls files and save them to their own client device hard drives. They can do that right...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.