C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » C# Syntax »

Export an SQL SERVER data table to an excel sheet


Posted Date: 22 Dec 2008    Resource Type: Code Snippets    Category: C# Syntax
Author: MASNSNMember Level: Gold    
Rating: 1 out of 5Points: 10




It's quite simple, you can create a stored procedure within SQL server and call the OPENROWSET method responsible for exporting data to a targeted excel sheet and you can pass the excel file as a parameter via the stored procedure
finally, you can call this procedure from within your C# code

This is the style of your SP

CREATE PROCEDURE ExportToExcel
(
@filepath nvarchar(100), -- OK you can change from 100 to the numenr that --fits your needs
@sheetname nvarchar(50)
)
INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 11.0;Database=C:\' + @filepath + ';',
'SELECT Name, Date FROM [' +@sheetname+ ']') SELECT * FROM yourdataTable
then you can call the stored procedure from within the C# code


string ConnectionString ="Integrated Security=SSPI;Initial Catalog=databasename;Data Source=servername;";
SqlConnection conn = new SqlConnection(ConnectionString);

SqlCommand StoredProcedureCommand = new SqlCommand("ExportToExcel", conn);
StoredProcedureCommand.CommandType = CommandType.StoredProcedure;
SqlParameter myParm1 = StoredProcedureCommand.Parameters.Add( "@filepath", SqlDbType.String);
myParm1.Value = @"C:\myfile.xlsx";
SqlParameter myParm2 = StoredProcedureCommand.Parameters.Add("@sheetname", SqlDbType.String);
myParm2.Value = "sheet$1";
conn.Open();
StoredProcedureCommand.excutenonequery;




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Export SQL SERVER to Excel with C#  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Sample program using feilds,constructors,properties
Previous Resource: Dispose the resource
Return to Discussion Resource Index
Post New Resource
Category: C# Syntax


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use