Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert created excel file using closed xml into bytes format

Hi I am using closedxML DLL for exporting to excel i have static method like this below

    public static void WriteToExcel(string fileName, List<CP> pages)
    {
        var wb = new XLWorkbook();
        byte[] file;


        var ws = wb.Worksheets.Add("CPs");
        WriteCostHeader(ws);

        ////write all the header columns
        //for (int i = 0; i < pages.Count; i++)
        int iRow = 2;
        foreach(var page in pages)
        {
            WriteCostPage(ws, page, iRow++);                

            WriteCostItemHead(ws, iRow++);

            foreach(var item in page.Items)
            {
                WriteCostItem(ws, item, iRow++);
            }
            iRow++;
        }

       wb.SaveAs(fileName);           
    }

I am calling above function in a method like this below

public  static List<CP> Init()
{

    //binding items to to list
}

static void Main(string[] args)
{
      byte[] file;
      file = ExcelProvider.WriteToExcel("D:\\Temp\\Test1.xls", Init());
      //Console.WriteLine("done");
      //Console.ReadLine();
 }

 public byte[] CreatePackage()
 {
     string fileName = string.Format("{0}.xlsx", "Generated");
     byte[] excelFile;         
     // getting error here cannot convert void to byte[]  
     excelFile =  ExcelProvider.WriteToExcel(fileName, Init());            
 }

but i need to get that result excel sheet in bytes, I need to store it in memory stream later i can use for further purpose ..

But I am not sure how can i get the created excel file in bytes format...

Would any one pls give any idea or solutions on this one ... Many thanks In advance ...

like image 597
Glory Raj Avatar asked Sep 30 '13 09:09

Glory Raj


1 Answers

Closed XML workbooks are saved to a stream. You can use a memory stream. Then call MemoryStream.ToArray() to get its bytes. So...

var wb = new XLWorkbook();
//...
var workbookBytes = new byte[0];
using (var ms = new MemoryStream())
{
    wb.SaveAs(ms);
    workbookBytes = ms.ToArray();
}
like image 147
Adam R. Grey Avatar answered Sep 19 '22 16:09

Adam R. Grey