0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

zipに圧縮してダウンロード

Posted at

はじめに

複数のファイルをzipでダウンロードしたいという要望がありました。
C#で開発していたこともあり、「ZipArchive」を使ってみました。

導入

参照に「System.IO.Compression」を追加します。
image.png

コード

usingディレクティブ

using System.IO.Compression;

を追加します。

zip圧縮

MemoryStream内で処理(ClosedXmlを使ったサンプル)

byte[] ret;
using (var ms = new MemoryStream())
{
    using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, true))
    {
        for (int i = 0; i < 5; i++)
        {
            // テンプレートファイルを読み込み
            using (var workbook = new XLWorkbook(@".\template\テンプレート.xlsx"))
            {
                // ブックを加工
                // …
                // ブックをstream変換
                using (var msBook = new MemoryStream())
                {
                    workbook.SaveAs(msBook);
                    byte[] retBook = msBook.ToArray();

                    using (Stream stream = zip.CreateEntry(i.ToString("0000") + ".xlsx", CompressionLevel.Optimal).Open())
                    {
                        stream.Write(retBook, 0, retBook.Length);
                    }
                }
            }
        }
    }
    ret = ms.ToArray();
}

上記の「ret」を送信してダウンロードさせる

public ActionResult DownloadExcel3()
{
    // 上記の「ret」を返却
    return File(ret, "application/octet-stream", "XXX.zip");
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?