There are too many questions to answer so i'll give you some pointers..Ill just assume youve got the stored procedure working although you may want to look into this a stored procedure to dynamically execute a query, so sneaky
A CSV writer library to output your file as a download. I should mention the output of csvwriter is a comma delimited list. So when you execute your stored procedure want to iterate over the returned rows along these lines...
public ActionResult DownloadCsv()
{
using (var memStream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(memStream))
{
var writer = new CsvWriter(streamWriter);
using (var conn = new SqlConnection(CONNECTION_STRING))
{
var command = new SqlCommand("YourStoredProcedure", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@id", id);
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine(reader.GetValue(i));
writer.WriteField(reader.GetValue(i));
}
writer.NextRecord();//you must also do this ALWAYS otherwise your .WriteFields wont be output for the current line
}
}
}
streamWriter.Flush();//note: you must flush
return File(memStream.ToArray(), "text/csv", "My 1337 download name.csv");
}
}
}
Did some research and here it is with zipping (without all the sql goo), you'll need this apparently uber popular library
public ActionResult DownloadCsv()
{
using (MemoryStream zippedDownloadStream = new MemoryStream())
{
using (ZipFile zip = new ZipFile())
{
using (var writerMemoryStream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(writerMemoryStream))
{
var writer = new CsvWriter(streamWriter);
//your writing
streamWriter.Flush();
}
zip.AddEntry("awesome file name.csv", writerMemoryStream.ToArray());
zippedDownloadStream.Flush();
zip.Save(zippedDownloadStream);
return File(zippedDownloadStream.ToArray(), "application/zip", "zippedup.zip");
}
}
}
}