473,769 Members | 4,227 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Conten tType = "applicatio n/vnd.ms-excel"
' Remove the charset from the Content-Type header.
Response.Charse t = ""
' Turn off the view state.
Me.EnableViewSt ate = False

Dim tw As New System.IO.Strin gWriter()
Dim hw As New System.Web.UI.H tmlTextWriter(t w)
' Get the HTML for the control.
DataGrid1.Rende rControl(hw)
' Write the HTML back to the browser.
Dim strFileName As String = "Roster_Export_ " &
m_objCourse.Cou rseKey.ToString .Replace("/", "_")

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

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

Dim _files As HttpFileCollect ion = HttpContext.Cur rent.Request.Fi les
Dim _message As System.Text.Str ingBuilder = New
System.Text.Str ingBuilder("Fil e Uploaded:<br>")
Dim sConnectionStri ng 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.Fil eName <> "" Then
_fileName = System.IO.Path. GetFullPath(_po stedFile.FileNa me)
' Create connection string variable. Modify the "Data Source"
parameter as
' appropriate for your environment.
'Dim sConnectionStri ng As String = BuildConnection String(_fileNam e)

sConnectionStri ng = "Provider=Micro soft.Jet.OLEDB. 4.0;"
sConnectionStri ng += "Data Source=" & _fileName & ";"
sConnectionStri ng += "Extended Properties=""Ex cel 8.0;HDR=YES;"""
' Create the connection object by using the preceding connection
string.
Dim objConn As New OleDbConnection (sConnectionStr ing)
' 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("S ELECT * FROM [Week2$] ",
objConn)
Dim objCmdSelect As New OleDbCommand("S ELECT * FROM [RosterExport$]
", objConn)
' Create new OleDbDataAdapte r that is used to build a DataSet
' based on the preceding SQL SELECT statement.

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

objAdapter1.Sel ectCommand = 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.Fil l(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 4531
This maybe helpful:

Export to Excel

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

Requires an asp.netPRO subscription.

Greg
"Jae" <ak*********@ea rthlink.net> wrote in message
news:22******** *************** ***@posting.goo gle.com...
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.Conten tType = "applicatio n/vnd.ms-excel"
' Remove the charset from the Content-Type header.
Response.Charse t = ""
' Turn off the view state.
Me.EnableViewSt ate = False

Dim tw As New System.IO.Strin gWriter()
Dim hw As New System.Web.UI.H tmlTextWriter(t w)
' Get the HTML for the control.
DataGrid1.Rende rControl(hw)
' Write the HTML back to the browser.
Dim strFileName As String = "Roster_Export_ " &
m_objCourse.Cou rseKey.ToString .Replace("/", "_")

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

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

Dim _files As HttpFileCollect ion = HttpContext.Cur rent.Request.Fi les
Dim _message As System.Text.Str ingBuilder = New
System.Text.Str ingBuilder("Fil e Uploaded:<br>")
Dim sConnectionStri ng 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.Fil eName <> "" Then
_fileName = System.IO.Path. GetFullPath(_po stedFile.FileNa me)
' Create connection string variable. Modify the "Data Source"
parameter as
' appropriate for your environment.
'Dim sConnectionStri ng As String = BuildConnection String(_fileNam e)

sConnectionStri ng = "Provider=Micro soft.Jet.OLEDB. 4.0;"
sConnectionStri ng += "Data Source=" & _fileName & ";"
sConnectionStri ng += "Extended Properties=""Ex cel 8.0;HDR=YES;"""
' Create the connection object by using the preceding connection
string.
Dim objConn As New OleDbConnection (sConnectionStr ing)
' 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("S ELECT * FROM [Week2$] ",
objConn)
Dim objCmdSelect As New OleDbCommand("S ELECT * FROM [RosterExport$]
", objConn)
' Create new OleDbDataAdapte r that is used to build a DataSet
' based on the preceding SQL SELECT statement.

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

objAdapter1.Sel ectCommand = 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.Fil l(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********@hot mail.com> wrote in message
news:e$******** ******@TK2MSFTN GP09.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*********@ea rthlink.net> wrote in message
news:22******** *************** ***@posting.goo gle.com...
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.Conten tType = "applicatio n/vnd.ms-excel"
' Remove the charset from the Content-Type header.
Response.Charse t = ""
' Turn off the view state.
Me.EnableViewSt ate = False

Dim tw As New System.IO.Strin gWriter()
Dim hw As New System.Web.UI.H tmlTextWriter(t w)
' Get the HTML for the control.
DataGrid1.Rende rControl(hw)
' Write the HTML back to the browser.
Dim strFileName As String = "Roster_Export_ " &
m_objCourse.Cou rseKey.ToString .Replace("/", "_")

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

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

Dim _files As HttpFileCollect ion = HttpContext.Cur rent.Request.Fi les
Dim _message As System.Text.Str ingBuilder = New
System.Text.Str ingBuilder("Fil e Uploaded:<br>")
Dim sConnectionStri ng 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.Fil eName <> "" Then
_fileName = System.IO.Path. GetFullPath(_po stedFile.FileNa me)
' Create connection string variable. Modify the "Data Source"
parameter as
' appropriate for your environment.
'Dim sConnectionStri ng As String = BuildConnection String(_fileNam e)

sConnectionStri ng = "Provider=Micro soft.Jet.OLEDB. 4.0;"
sConnectionStri ng += "Data Source=" & _fileName & ";"
sConnectionStri ng += "Extended Properties=""Ex cel 8.0;HDR=YES;"""
' Create the connection object by using the preceding connection
string.
Dim objConn As New OleDbConnection (sConnectionStr ing)
' 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("S ELECT * FROM [Week2$] ",
objConn)
Dim objCmdSelect As New OleDbCommand("S ELECT * FROM [RosterExport$]
", objConn)
' Create new OleDbDataAdapte r that is used to build a DataSet
' based on the preceding SQL SELECT statement.

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

objAdapter1.Sel ectCommand = 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.Fil l(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 = ExecuteReportRe turnDataSet();
// write them out to disk
string exportPath = Facade.Export.E xportDataSet(
dsReport,
Session["UserLogin"].ToString(),
ConfigurationSe ttings.AppSetti ngs["ApplicationPat h"].ToString() +
ConfigurationSe ttings.AppSetti ngs["ReportPath "].ToString(),
ConfigurationSe ttings.AppSetti ngs["ApplicationPat h"].ToString() +
@"xsl\gb_report _flash.xsl",
Convert.ToInt32 (cUIHelper.Expo rtFormat.Export Xls).ToString() );

// Write the Report to the Browser
Response.ClearC ontent();
Response.ClearH eaders();
Response.Conten tType = "applicatio n/vnd.ms-excel";
Response.WriteF ile(exportPath) ;
Response.Flush( );
Response.Close( );

System.IO.File. Delete(exportPa th);

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

switch ((ExportFormat) Convert.ToInt32 (ExportFormatCh oice))
{
case (ExportFormat.E xportXls):
exportPath = FilePath + UserName + "_SearchResults .xls";
break;
case (ExportFormat.E xportHtml):
exportPath = FilePath + UserName + "_SearchResults .html";
break;
}

// Create a FileStream to write with
System.IO.FileS tream fs = new System.IO.FileS tream(
exportPath, System.IO.FileM ode.Create);
// Create an XmlTextWriter for the FileStream
System.Xml.XmlT extWriter xtw = new System.Xml.XmlT extWriter(
fs, System.Text.Enc oding.Unicode);
try
{
XmlDataDocument xmlDoc = new XmlDataDocument (SearchResults) ;
System.Xml.Xsl. XslTransform xslTran = new System.Xml.Xsl. XslTransform();
xslTran.Load(Xs lPath);
xslTran.Transfo rm(xmlDoc, null, xtw);
xtw.Close();
return exportPath;
}
catch (Exception ex)
{
xtw.Close();
System.IO.File. Delete(exportPa th);
ExceptionManage r.Publish(ex);
throw(ex);
}
}
#endregion
Nov 17 '05 #4
Jae
"George Durzi" <gdurzi@nospam_ hotmail.com> wrote in message news:<eH******* *******@tk2msft ngp13.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
1085
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 codings. The web layout is designed in with frame, using client script. Below are the tested result:
2
2187
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 at the time the users request it. My initial plan is that when users request their data, they will click a button or link indicating that they want their data in the respective file format. Then, on the server I want to execute a stored...
5
3507
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 that when the user click on the button a popup appear in IE to say "Do you want to save or open file?"
6
2698
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 the excel document. When I click save I can save the excel document or when I click open it directly opens in excel. This works fine for all but one machine. On one machine however the dialog prompts to open or save the excel document (e.g....
2
2807
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 'FindWindow' API. How can I send 'save' command to external excel window? Actual thing I want to do is I can handle excel application in the winform. My client hope that all staff can use excel application in new window
3
4470
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 spreadsheet with the accurate data. 2) The .CSV file is saved from the server to the local hard drive of the client. 3) An Excel spreadsheet is already running on the client (version 2002
6
4117
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 analytical results (from a PostgreSQL database) and the parameters the user selected on a page as a series of table, etc - with the number of results and hence the number of "little tables" being related to what parameters they chose. The...
3
7162
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 file but save it as an excel file. The data in this excel file will be imported into an Access database. The
3
4356
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 now the way I have this set up, but it's confusing and slow. When they browse for a place to save the reports, they see all of the drives on the terminal server as well as their own client drives. So they're likely to want to choose "My...
0
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10199
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9981
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9850
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7396
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6662
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5293
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3551
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2810
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.