473,583 Members | 3,567 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exporting Data Set to Excel

Could someone please provide me an effective means of
exporting data from a data set (or data grid) to Excel?
Jul 21 '05 #1
3 7991
You might want to try ReportDepot for .NET
(www.semurg.ca) Since v. 02.00.00 it can sav report
output to Excel file

HTH
-----Original Message-----
Could someone please provide me an effective means of
exporting data from a data set (or data grid) to Excel?
.

Jul 21 '05 #2
The DataAdapter is designed for this sort of task.
If you obtained your DataSet from an OLEDB database, you may have used a
System.Data.Ole db.OledbDataAda pter and the DataAdapter.Fil l() method to get
it.
And you know there is a Update() method, as well, on the DataAdapter.
You can set the UpdateCommand on the DataAdapter to refer to an MS-Excel
file, via the OLEDB provider for MS Excel.
You also need to set the Connection on the UpdateCommand.
And you will need to "create the table" in the MS-Excel datasource before
inserting.

A working example follows.

If you obtained your dataset from a non-OLEDB DataAdapter (say, for example,
the System.Data.Sql Client.DataAdap ter), then you can use the same technique,
but with 2 distinct DataAdapters. The MS-Excel is accessible only via the
OLEDB DataAdapter, as far as I know. So you would do something like:
dataAdapter1.Fi ll(dataSet1);
dataAdapter2.Up date(dataSet1);
--
Dino Chiesa
Microsoft Developer Division
d i n o c h @ O N L I N E . m i c r o s o f t . c o m

// ExtractToExcel. cs
//
// uses a single DataSet and DataAdapter to copy data from one database
(SQL)
// to another (MS Excel, via Jet Driver)
//
// Wed, 01 Oct 2003 19:32
//

namespace Ionic {

public class ExtractToExcel {

public static void Main(string[] args) {
ExtractToExcel e= new ExtractToExcel( );
e.Run();
}

const string ConnStringSourc e= "Provider=sqlol edb;Data
Source=dinoch-1\\vsdotnet;Ini tial Catalog=Northwi nd;Integrated
Security=SSPI;" ;
const string OutputFilename= "ExtractToExcel .xls";

const string ConnStringDest=
"Provider=Micro soft.Jet.OLEDB. 4.0;" +
"Data Source=" + OutputFilename + ";" +
"Extended Properties=\"Ex cel 8.0;HDR=yes;\"" ; //
FIRSTROWHASNAME S=1;READONLY=fa lse\"

private System.Data.Ole Db.OleDbConnect ion ConnSource= null;
private System.Data.Ole Db.OleDbConnect ion ConnDest= null;

const string sqlSelect="SELE CT top 10 ProductId, ProductName,
QuantityPerUnit , UnitPrice, UnitsInStock, GETDATE() as Extracted from
Products order by UnitPrice";
const string sqlInsert="INSE RT INTO Extracto (ProductId, ProductName,
QuantityPerUnit , UnitPrice, UnitsInStock, Extracted) VALUES (@ProductId,
@ProductName, @QuantityPerUni t, @UnitPrice, @UnitsInStock, @Extracted)";
const string sqlCreate = "CREATE TABLE Extracto ( ProductId NUMBER,
ProductName char(40), QuantityPerUnit char(20), UnitPrice NUMBER,
UnitsInStock NUMBER, Extracted DATETIME )";

System.Data.Ole Db.OleDbDataAda pter da ;
System.Data.Dat aSet ds;

public void CreateTable() {
System.Console. WriteLine("Crea ting table in Excel file...");

ConnDest= new System.Data.Ole Db.OleDbConnect ion(ConnStringD est);
System.Data.Ole Db.OleDbCommand cmd= new
System.Data.Ole Db.OleDbCommand (sqlCreate, ConnDest);
try {
ConnDest.Open() ;
cmd.ExecuteNonQ uery();
}
catch (System.Excepti on e2){
if (!e2.Message.Tr im().EndsWith(" already exists."))
System.Console. WriteLine("Erro r while creating. " + e2);
else
System.Console. WriteLine("File and Table (worksheet) already
exist...");
}
finally {
ConnDest.Close( );
}
}
private void Read() {
System.Console. WriteLine("Read ing from SQL...");
ConnSource= new System.Data.Ole Db.OleDbConnect ion(ConnStringS ource);
da= new System.Data.Ole Db.OleDbDataAda pter();
da.SelectComman d= new System.Data.Ole Db.OleDbCommand (sqlSelect);
da.SelectComman d.Connection= ConnSource;

ds= new System.Data.Dat aSet();
da.Fill(ds, "Extracto") ;
//System.Console. WriteLine("data : \n" + ds.GetXml());
}

private void InsertIntoExcel () {
System.Console. WriteLine("Inse rting data into Excel...");
// need to update the row so the DA does the insert...
foreach (System.Data.Da taRow r in ds.Tables[0].Rows) {
r["Extracted"]= System.DateTime .Now; // update the row!
}

da.UpdateComman d= new System.Data.Ole Db.OleDbCommand (sqlInsert);
da.UpdateComman d.Connection= ConnDest;

da.UpdateComman d.Parameters.Ad d("@ProductId ",
System.Data.Ole Db.OleDbType.In teger, 4, "ProductId" );
da.UpdateComman d.Parameters.Ad d("@ProductName ",
System.Data.Ole Db.OleDbType.Va rWChar, 40, "ProductNam e");
da.UpdateComman d.Parameters.Ad d("@QuantityPer Unit",
System.Data.Ole Db.OleDbType.Va rWChar, 20, "QuantityPerUni t");
da.UpdateComman d.Parameters.Ad d("@UnitPrice ",
System.Data.Ole Db.OleDbType.Cu rrency, 8, "UnitPrice" );
da.UpdateComman d.Parameters.Ad d("@UnitsInStoc k",
System.Data.Ole Db.OleDbType.Sm allInt, 2, "UnitsInStock") ;
da.UpdateComman d.Parameters.Ad d("@Extracted ",
System.Data.Ole Db.OleDbType.Da te, 8, "Extracted" );

da.Update(ds, "Extracto") ;

// in the event you want to update a datasource via a different
DataAdapter --
// for example you want to fill from a
System.Data.Sql Client.DataAdap ter and
// then Update via a System.Data.Ole db.OledbDataAda pter -- then you
could define
// two distinct DataAdapters. Fill the DataSet with the first DA,
then Update
// with the second DA.
}

private void OpenResultInExc el() {
System.Console. WriteLine("Star ting MS-Excel...");
System.Diagnost ics.Process.Sta rt(OutputFilena me);
}

public void Run() {
try {
Read();
CreateTable();
InsertIntoExcel ();

OpenResultInExc el();

}
catch (System.Excepti on e1) {
System.Console. WriteLine("Exce ption: " + e1 );
}
}
}
}

"Chris" <ch*********@tb gamericas.com> wrote in message
news:00******** *************** *****@phx.gbl.. .
Could someone please provide me an effective means of
exporting data from a data set (or data grid) to Excel?

Jul 21 '05 #3
This is very helpful only thing is how to I add to
multiple spreadsheets and name those tabs?
-----Original Message-----
The DataAdapter is designed for this sort of task.
If you obtained your DataSet from an OLEDB database, you may have used aSystem.Data.Ol edb.OledbDataAd apter and the DataAdapter.Fil l() method to getit.
And you know there is a Update() method, as well, on the DataAdapter.You can set the UpdateCommand on the DataAdapter to refer to an MS-Excelfile, via the OLEDB provider for MS Excel.
You also need to set the Connection on the UpdateCommand.
And you will need to "create the table" in the MS-Excel datasource beforeinserting.

A working example follows.

If you obtained your dataset from a non-OLEDB DataAdapter (say, for example,the System.Data.Sql Client.DataAdap ter), then you can use the same technique,but with 2 distinct DataAdapters. The MS-Excel is accessible only via theOLEDB DataAdapter, as far as I know. So you would do something like: dataAdapter1.Fi ll(dataSet1);
dataAdapter2.Up date(dataSet1);
--
Dino Chiesa
Microsoft Developer Division
d i n o c h @ O N L I N E . m i c r o s o f t . c o m

// ExtractToExcel. cs
//
// uses a single DataSet and DataAdapter to copy data from one database(SQL)
// to another (MS Excel, via Jet Driver)
//
// Wed, 01 Oct 2003 19:32
//

namespace Ionic {

public class ExtractToExcel {

public static void Main(string[] args) {
ExtractToExcel e= new ExtractToExcel( );
e.Run();
}

const string ConnStringSourc e= "Provider=sqlol edb;Data
Source=dinoc h-1\\vsdotnet;Ini tial Catalog=Northwi nd;IntegratedSecurity=SSPI; " ;
const string OutputFilename= "ExtractToExcel .xls";

const string ConnStringDest=
"Provider=Micro soft.Jet.OLEDB. 4.0;" +
"Data Source=" + OutputFilename + ";" +
"Extended Properties=\"Ex cel 8.0;HDR=yes;\"" ; //
FIRSTROWHASNAM ES=1;READONLY=f alse\"

private System.Data.Ole Db.OleDbConnect ion ConnSource= null; private System.Data.Ole Db.OleDbConnect ion ConnDest= null;
const string sqlSelect="SELE CT top 10 ProductId, ProductName,QuantityPerUni t, UnitPrice, UnitsInStock, GETDATE() as Extracted fromProducts order by UnitPrice";
const string sqlInsert="INSE RT INTO Extracto (ProductId, ProductName,QuantityPerUni t, UnitPrice, UnitsInStock, Extracted) VALUES (@ProductId,@ProductName , @QuantityPerUni t, @UnitPrice, @UnitsInStock, @Extracted)"; const string sqlCreate = "CREATE TABLE Extracto ( ProductId NUMBER,ProductName char(40), QuantityPerUnit char(20), UnitPrice NUMBER,UnitsInStock NUMBER, Extracted DATETIME )";

System.Data.Ole Db.OleDbDataAda pter da ;
System.Data.Dat aSet ds;

public void CreateTable() {
System.Console. WriteLine("Crea ting table in Excel file...");
ConnDest= new System.Data.Ole Db.OleDbConnect ion (ConnStringDest ); System.Data.Ole Db.OleDbCommand cmd= new
System.Data.Ol eDb.OleDbComman d(sqlCreate, ConnDest);
try {
ConnDest.Open() ;
cmd.ExecuteNonQ uery();
}
catch (System.Excepti on e2){
if (!e2.Message.Tr im().EndsWith(" already exists.")) System.Console. WriteLine("Erro r while creating. " + e2); else
System.Console. WriteLine("File and Table (worksheet) alreadyexist...");
}
finally {
ConnDest.Close( );
}
}
private void Read() {
System.Console. WriteLine("Read ing from SQL...");
ConnSource= new System.Data.Ole Db.OleDbConnect ion (ConnStringSour ce); da= new System.Data.Ole Db.OleDbDataAda pter();
da.SelectComman d= new System.Data.Ole Db.OleDbCommand (sqlSelect); da.SelectComman d.Connection= ConnSource;

ds= new System.Data.Dat aSet();
da.Fill(ds, "Extracto") ;
//System.Console. WriteLine("data : \n" + ds.GetXml ()); }

private void InsertIntoExcel () {
System.Console. WriteLine("Inse rting data into Excel..."); // need to update the row so the DA does the insert... foreach (System.Data.Da taRow r in ds.Tables [0].Rows) { r["Extracted"]= System.DateTime .Now; // update the row! }

da.UpdateComman d= new System.Data.Ole Db.OleDbCommand (sqlInsert); da.UpdateComman d.Connection= ConnDest;

da.UpdateComman d.Parameters.Ad d("@ProductId ",
System.Data.Ol eDb.OleDbType.I nteger, 4, "ProductId" );
da.UpdateComman d.Parameters.Ad d("@ProductName ",
System.Data.Ol eDb.OleDbType.V arWChar, 40, "ProductNam e");
da.UpdateComman d.Parameters.Ad d ("@QuantityPerU nit",System.Data.Ol eDb.OleDbType.V arWChar, 20, "QuantityPerUni t"); da.UpdateComman d.Parameters.Ad d("@UnitPrice ",
System.Data.Ol eDb.OleDbType.C urrency, 8, "UnitPrice" );
da.UpdateComman d.Parameters.Ad d("@UnitsInStoc k",
System.Data.Ol eDb.OleDbType.S mallInt, 2, "UnitsInStock") ;
da.UpdateComman d.Parameters.Ad d("@Extracted ",
System.Data.Ol eDb.OleDbType.D ate, 8, "Extracted" );

da.Update(ds, "Extracto") ;

// in the event you want to update a datasource via a differentDataAdapter --
// for example you want to fill from a
System.Data.Sq lClient.DataAda pter and
// then Update via a System.Data.Ole db.OledbDataAda pter -- then youcould define
// two distinct DataAdapters. Fill the DataSet with the first DA,then Update
// with the second DA.
}

private void OpenResultInExc el() {
System.Console. WriteLine("Star ting MS-Excel...");
System.Diagnost ics.Process.Sta rt(OutputFilena me);
}

public void Run() {
try {
Read();
CreateTable();
InsertIntoExcel ();

OpenResultInExc el();

}
catch (System.Excepti on e1) {
System.Console. WriteLine("Exce ption: " + e1 );
}
}
}
}

"Chris" <ch*********@tb gamericas.com> wrote in message
news:00******* *************** ******@phx.gbl. ..
Could someone please provide me an effective means of
exporting data from a data set (or data grid) to Excel?

.

Jul 21 '05 #4

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

Similar topics

3
9233
by: sridevi | last post by:
Hello How to export data from ms-access database to excel worksheet using ASP. mainly i need to export data to multiple worksheets. it is very urgent to us. i have a sample code which works only exporting to single worksheet. but i need to export data to multiple worksheets. it is very urgent to us. so please help me in code.
4
3939
by: D | last post by:
I've created a report with many subreports of aggregate data. I want my client to be able to export this data to Excel to make her charts, etc. Only one problem: one of the fields is a "SchoolYear" TEXT field that contains data such as 2000/01, 2001/02, etc. If I export a Query with this kind of data to Excel, it gives me the text value of...
2
7700
by: G | last post by:
When I export data from access to excel by with "export" or "Analyze with" I seem to loose parts of some fields (long text strings). Is there a way to export it all to excel? Thanks G
2
2301
by: pmud | last post by:
Hi, I am exporting data from an EDITABLE DATA GRID EXCEL. But the 1st column in data grid is Edit Column. I want to display all columns in Excel except for the Edit column. The following code which I am using allows exporting only from text data from data grid & not from Edit columns which are link buttons. How to leave this column...
3
352
by: Chris | last post by:
Could someone please provide me an effective means of exporting data from a data set (or data grid) to Excel?
2
2396
by: bienwell | last post by:
Hi, I have a question about exporting data from datagrid control into Excel file in ASP.NET. On my Web page, I have a linkbutton "Export data". This link will call a Sub Function to perform exporting ALL data from the datagrid control. Exporting data works fine when I show all data on the datagrid control. I'd like to shows only 30...
2
3165
by: Snozz | last post by:
The short of it: If you needed to import a CSV file of a certain structure on a regular basis(say 32 csv files, each to one a table in 32 databases), what would be your first instinct on how to set this up so as to do it reliably and minimize overhead? There are currently no constraints on the destination table. Assume the user or some...
1
6953
by: 333sridhar333 | last post by:
Hi, I am having a problem in exporting a data from jsp to excel. I am getting the values from a servlet and populating it to a JSP. And form there i export them to Excel. The functionality works fine. But the problem is with the exported data. I am having values with leading zeros. for example: Patron Code
2
3573
by: 333sridhar333 | last post by:
Hi, I am having a problem in exporting a data from jsp to excel. I am getting the values from a servlet and populating it to a JSP. And form there i export them to Excel. The functionality works fine. But the problem is with the exported data. I am having values with leading zeros. for example: Patron Code
0
7893
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...
0
8172
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. ...
0
8317
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7928
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...
0
6574
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5695
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...
0
3839
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1422
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1151
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...

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.