2

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.

Community
  • 1
  • 1
ZVenue
  • 4,967
  • 16
  • 61
  • 92

1 Answers1

3
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");
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Sorry I just edited the OP with modified code.. I forgot about the streamwriter part of the code.. thanks for your help – ZVenue Mar 07 '12 at 19:16
  • @ZVenue, I absolutely don't see how your modified code has anything to do with the excellibrary. In order to use it you need to build a DataSet and pass it to the CreateWorkbook method as illustrated in the post you have linked to. You seem to have some existing code that generates a CSV file. You will have to modify it. Read the documentation of the product you are using. It will help you in this task. – Darin Dimitrov Mar 07 '12 at 19:16
  • basically I need to change how I write the output.. to a dataset from a stream. – ZVenue Mar 07 '12 at 19:19
  • @ZVenue, I don't see what your question has to do with ASP.NET MVC in fact? – Darin Dimitrov Mar 07 '12 at 19:20
  • I changed the writer to dataset and modified the code accordingly.. its working great. thank you – ZVenue Mar 07 '12 at 21:07