MiniExcel icon indicating copy to clipboard operation
MiniExcel copied to clipboard

How To Wirte to MemoryStream from IDataReader

Open dongfo opened this issue 2 years ago • 3 comments

Excel Type

  • [ x] XLSX
  • [ ] XLSM
  • [ ] CSV
  • [ ] OTHER

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.

dongfo avatar Jun 29 '22 03:06 dongfo

@dongfo MiniExcel.SaveAs(yourstream, yourreader);

shps951023 avatar Jun 30 '22 14:06 shps951023

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");

dongfo avatar Jul 09 '22 14:07 dongfo

waht is Fie?

Jahong1rSuyunov avatar Nov 10 '23 12:11 Jahong1rSuyunov