问题
I have a MS SQL view that I want to make available as a CSV download in my ASPNET Web Forms app. I am using Entity Framework for other views and tables in the project. What's the best way to enable this download?
I could add a LinkButton whose click handler iterates over the view, writes its CSV form to the disk, and then serves that file. However, I'd prefer not to write to the disk if it can be avoided, and that involves iteration code that may be avoided with some other solution.
回答1:
You could iterate over the dataset, but instead of creating the CSV file on your server simply return it through the HTTP response. The following function should do the trick.
Public Shared Sub ExportTextFile(ByVal response As System.Web.HttpResponse, ByVal text As String, ByVal fileName As String)
response.Clear()
response.AddHeader("content-disposition", String.Format("attachment;filename={0}", fileName))
response.Charset = ""
response.Cache.SetCacheability(HttpCacheability.NoCache)
response.ContentType = "application/vnd.text"
Dim stringWrite As New System.IO.StringWriter
Dim htmlWrite = New HtmlTextWriter(stringWrite)
response.Write(text.ToString)
response.End()
End Sub
回答2:
See this article, specifically the method WriteToCsv();
This will send the csv data to the browser as PersonList.csv
.
Update: Possible Asp.Net scenario:
protected void Page_Load(object sender, EventArgs e)
{
var data = GetMyData(...);
CSVExporter.WriteToCSV(data);
}
回答3:
Here is my code to ceate a csv file from any IDataReader. Call it using the results of an ExecuteReader() and HttpResponse.OutputStream. It will write out the column names in the first row, then one or more sets of data rows. Output it to the browser as suggested by matt, though I would suggest content type 'text/csv'.
public static void createCsvFile(IDataReader reader, StreamWriter writer) {
for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++) {
if (columnCounter > 0) {
writer.Write(Separator);
}
writer.Write(Delimiter + reader.GetName(columnCounter) + Delimiter);
}
writer.WriteLine(string.Empty);
do {
while (reader.Read()) {
for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++) {
if (columnCounter > 0) {
writer.Write(Separator);
}
writer.Write("\""+ reader.GetValue(columnCounter).ToString().Replace('"', '\'') + "\"");
}
writer.WriteLine(string.Empty);
}
writer.Flush();
}
while (reader.NextResult());
回答4:
I found this question, which addresses the HttpHandler portion of the dilemma.
In ASP.NET, how to get the browser to download string content into a file? (C#)
来源:https://stackoverflow.com/questions/2540368/how-to-serve-a-view-as-csv-in-asp-net-web-forms