Output to Excel using ExcelLibrary in c#

ZVenue picture ZVenue · Mar 7, 2012 · Viewed 9.6k times · Source

The following code outputs to a csv file using controller.file. I want to change it to input to an excel sheet (.xls) instead of a csv file. I a using this library from here to do this.. http://code.google.com/p/excellibrary/

as per this stackoverflow post.. Create Excel (.XLS and .XLSX) file from C#

Edit:

foreach (var value in valueDataList)

    {
        var value1 = xxxxxxx    // this value is set here based on a query.. 
        int value2 = xxxxxxxx   // this value is set here based on a query.. 

        byte[] content;

        using (var ms = new MemoryStream())  
           {
              using (var writer = new StreamWriter(ms))
                {
                  writer.WriteLine("ValueHeading1   " + " ValueHeading2");
                  writer.WriteLine(value1 + "              " + value2);                         
                }
                  content = ms.ToArray();
                  return File(content, "text/csv", "demo.csv");
            //ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelTest.xls", content);

           }
    }   

How can I modify my existing code to putput to excel using this library. The last commented line in the code does not work because it expects 'content' to be a dataset and not a byte.. thanks for any help.

Answer

Darin Dimitrov picture Darin Dimitrov · Mar 7, 2012
public ActionResult Excel()
{
    DataSet ds = ...
    using (var ms = new MemoryStream())  
    {
        ExcelLibrary.DataSetHelper.CreateWorkbook(ms, ds)
        return File(ms.ToArray(), "application/vnd.ms-excel", "demo.xls");
    }
}