簡體   English   中英

ASP.NET 下載 csv 文件為 zip?

[英]ASP.NET download csv file as zip?

我一直在閱讀:

https://www.aspsnippets.com/Articles/Export-data-from-SQL-Server-to-CSV-file-in-ASPNet-using-C-and-VBNet.aspx

而不是像 csv 中描述的那樣只能選擇下載:

                //Download the CSV file.
                Response.Clear();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
                Response.Charset = "";
                Response.ContentType = "application/text";
                Response.Output.Write(csv);
                Response.Flush();
                Response.End();

有沒有辦法使用本機 asp.net 到第一個 zip csv output 來自 Response.Output.Write(csv) 中的 csv 變量; 以便用戶下載 SqlExport.zip 而不是 SqlExport.csv?

大致基於,您可以創建一個 zip 文件,同時將其推流到客戶端;

Response.ContentType = "application/octet-stream";
Response.Headers.Add("Content-Disposition", "attachment; filename=\"SqlExport.zip\"");

using var archive = new ZipArchive(Response.Body, ZipArchiveMode.Create);

var entry = archive.CreateEntry("SqlExport.csv");
using var entryStream = entry.Open();

entryStream.Write(csv); // write the actual content here

entryStream.Flush();

雖然不是附加到單個csv字符串,您應該考慮使用StreamWriter將每個文本片段直接寫入響應 stream。從鏈接的 csv 示例中替換;

using var sw = new StreamWriter(entryStream);

// TODO write header

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        //Add the Data rows.
        await sw.WriteAsync(row[column.ColumnName].ToString().Replace(",", ";") + ',');
    }
    //Add new line.
    await sw.WriteLineAsync();
}

盡管這是 csv 文件的一個糟糕示例。 而不是替換';' 字符,字符串應該被引用並轉義所有引號。

然而Response.Body僅在 .net 5 / core 中可用。 要在 .net 4.8 或更早版本中直接寫入 http 響應,您必須編寫自己的HttpContent 將所有東西放在一起,包括更好的 csv 格式化程序;

public class ZipContent : HttpContent
{
    private DataTable dt;
    private string name;

    public ZipContent(DataTable dt, string name = null)
    {
        this.dt = dt;
        this.name = name ?? dt.TableName;
        Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
        Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = $"{name}.zip"
        };
    }

    private string formatCsvValue(string value)
    {
        if (value == null)
            return "";
        if (value.Contains('"') || value.Contains(',') || value.Contains('\r') || value.Contains('\n'))
            return $"\"{value.Replace("\"", "\"\"")}\"";
        return value;
    }

    private IEnumerable<DataColumn> Columns()
    {
        // Why is this not already an IEnumerable<DataColumn>?
        foreach (DataColumn col in dt.Columns)
            yield return col;
    }

    protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
    {
        using var archive = new ZipArchive(stream, ZipArchiveMode.Create);

        var entry = archive.CreateEntry($"{name}.csv");
        using var entryStream = entry.Open();
        using var sw = new StreamWriter(entryStream);

        await sw.WriteLineAsync(
            string.Join(",",
                Columns()
                .Select(c => formatCsvValue(c.ColumnName))
            ));

        foreach (DataRow row in dt.Rows)
        {
            await sw.WriteLineAsync(
                string.Join(",", 
                    row.ItemArray
                    .Select(o => formatCsvValue(o?.ToString()))
                ));
        }
    }

    protected override bool TryComputeLength(out long length)
    {
        length = 0;
        return false;
    }
}

看看ZipArchive Class

你可以使用public System.IO.Compression.ZipArchiveEntry CreateEntry (string entryName); 創建一個 ZipEntry 並將其添加到存檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM