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.

1 Answer 1

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");
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry I just edited the OP with modified code.. I forgot about the streamwriter part of the code.. thanks for your help
@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.
basically I need to change how I write the output.. to a dataset from a stream.
@ZVenue, I don't see what your question has to do with ASP.NET MVC in fact?
I changed the writer to dataset and modified the code accordingly.. its working great. thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.