Share via


How to convert Excel WorkBook into Bytes

Question

Wednesday, December 15, 2010 9:27 AM

Hi,

I want to convert the Excel workbook or Excel into Bytes

my code

 public static Byte[] CreateExcelBytes(List<string> Columns, List<CompanySearchResultItem> collection)
    {
      Excel.Application xlApp;
      Excel.Workbook xlWorkBook;
      
      //New Excel
      xlApp = new Excel.Application();

      //WorkBook
      Excel.Workbooks wks = xlApp.Workbooks;
      xlWorkBook = wks.Add();

      //Active Work Sheet
      Excel.Worksheet sheet = xlWorkBook.ActiveSheet;
      
      //Cells
      Excel.Range cells = sheet.Cells;

      //string[] array = collection.ToArray<T>();

      for (int rowIndex = 1; rowIndex < collection.Count; rowIndex++)
      {
        for (int j = 0; j < 2; j++)
        {
          cells[rowIndex][1] = collection[rowIndex].CompanyName.ToString();
          cells[rowIndex][2] = collection[rowIndex].CompanyTypeId.ToString();
        }
      }

now cells contains the records

how to convert them into Array of Bytes so that at client side i can use this Bytes and Make the excel file out of them

All replies (4)

Thursday, December 16, 2010 12:42 PM âś…Answered

Hi ,

I got the solution

u need to first save the File ..

and then u can read bytes using FileStream

i think there's no way to get the bytes out of unsaved file

 


Wednesday, December 15, 2010 9:54 AM

Rhao,

It is not my kind of subject, but did you know that if you start a new question instead of a discussion you have a better chance on an answer. 

You can change it in top of your original message.

 

Success
Cor


Thursday, December 16, 2010 11:15 AM

THanks Cor Lighert


Thursday, December 16, 2010 11:55 AM

I would suggest you, instead of collecting data in 'cells'(What you are doing here),

 for (int rowIndex = 1; rowIndex < collection.Count; rowIndex++)



   {



    for (int j = 0; j < 2; j++)



    {



     cells[rowIndex][1] = collection[rowIndex].CompanyName.ToString();



     cells[rowIndex][2] = collection[rowIndex].CompanyTypeId.ToString();



    }



   }

You can put it in memorystream. Then create a byte array like,

byte[] byteArray = new byte[memorystream.Length];

memorystream.Read(byteArray, 0 byteArray.Length);

 

Check it....

Santosh.