Sunday, May 29, 2011

Very quick way to generate Excel file from C#. LOVE IT!

Download the DLL from Google Code and include it in the C# project.
http://code.google.com/p/excellibrary/

//Create the dataset
DataSet ds = new DataSet();

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Create connection
SqlConnection sConn = new SqlConnection();
sConn.ConnectionString = ConnectionString;
sConn.Open();

// Execute stored procedure and fill dataset
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "sp_sample_stored_procedure";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sConn;

SqlParameter param = new SqlParameter("Name", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = name;
cmd.Parameters.Add(param);

SqlDataAdapter sAdapter = new SqlDataAdapter(cmd);
sAdapter.Fill(ds);
sConn.Close();

//Populate Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("file.xls", ds);

No comments:

Related Posts Plugin for WordPress, Blogger...