mini-software / MiniExcel

Fast, Low-Memory, Easy Excel .NET helper to import/export/template spreadsheet (support Linux, Mac)
https://www.nuget.org/packages/MiniExcel/
Apache License 2.0
2.78k stars 337 forks source link

How To Wirte to MemoryStream from IDataReader #403

Open dongfo opened 2 years ago

dongfo commented 2 years ago

Excel Type

Upload Excel File

Please attach your issue file by dragging or droppng, selecting or pasting them.

MiniExcel Version

MiniExcel 1.26.4

Description

as docs descriped saveAs to MemoryStream like this

public IActionResult DownloadExcel()
{
    var values = new[] {
        new { Column1 = "MiniExcel", Column2 = 1 },
        new { Column1 = "Github", Column2 = 2}
    };

    var memoryStream = new MemoryStream();
    memoryStream.SaveAs(values);
    memoryStream.Seek(0, SeekOrigin.Begin);
    return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    {
        FileDownloadName = "demo.xlsx"
    };
}

to void load all data into memory ,I chose IDataReader

using (var cnn = Connection)
{
    cnn.Open();
    var sheets = new Dictionary<string,object>();
    sheets.Add("sheet1", cnn.ExecuteReader("select 1 id"));
    sheets.Add("sheet2", cnn.ExecuteReader("select 2 id"));
    MiniExcel.SaveAs("Demo.xlsx", sheets);
}

I want to combine them, Create excel and direct to memorystream for download.

shps951023 commented 2 years ago

@dongfo MiniExcel.SaveAs(yourstream, yourreader);

dongfo commented 2 years ago

It works for me . down load excel file like this.

 using var db = new SqlConnection("....");
 using var cmd = new SqlCommand("select * from table", db);
 using var reader = await cmd.ExecuteReaderAsync(CommandBehavior.SequentialAccess);
 var excelStream = new MemoryStream();
 await MiniExcel.SaveAsAsync(excelStream, reader);
 excelStream.Seek(0, SeekOrigin.Begin);
return Fie(excelStream,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","export.xlsx");

and more ,when I try to zip this file and It's okay to create and download zip file.But the zip file can't open.

 using var db = new SqlConnection("....");
 using var cmd = new SqlCommand("select * from table", db);
 using var reader = await cmd.ExecuteReaderAsync(CommandBehavior.SequentialAccess);
 var excelStream = new MemoryStream();
 await MiniExcel.SaveAsAsync(excelStream, reader);
 excelStream.Seek(0, SeekOrigin.Begin);
 var outStream = new MemoryStream();
 using var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true);

 var csvFile = archive.CreateEntry($"export_{DateTime.Now:yyyyMMdd}.xlsx");
 using var entryStream = csvFile.Open();
 await excelStream.CopyToAsync(entryStream);
 outStream.Seek(0, SeekOrigin.Begin);
return Fie(excelStream,"application/zip","export.zip");
Jahong1rSuyunov commented 11 months ago

waht is Fie?