Export to Excel from a List in .Net

Help!

I need to export a list from a custom entity. The custom entity's list page was generated using .net (RunListPage).

I found an example on the community on how to do this with an asp page. However, I cannot find any assistance in doing this in the .net.

Can someone point me in the right direction or provide an example.

Any assistance would be greatly appreciated. Thanks!

  • 0

    I have found a way to do it. Definitely not the "cleanest" thing. What I did was create a custom class called exportdata. I then create a button on the screen I want to export from to call this class. The button click when calling the exportdata provides all information from a filter and what page I was on in the query string.

    I then rebuild the where clause from the querystrings and use the QuerySelect to obtain my list of items.

    Then I convert all items from that queryselect reader one at a time into a list of .

    Then I write the file to a temp directory on the CRM server.

    Then I use AddContent and add the file location to the ExportData screen. This will prompt the user to download the file. and then redirect back to the original page.

  • 0

    Thanks Brad...

    I will give this a try. I was hoping it was already built in and I was just missing it. I will let you know if I am successful with this.

    Thanks Again!

  • 0

    Yeah, let me know how it goes. If need be I can post some code in here. I'm just lazy and didn't want to strip out things to post it the first time.

  • 0

    Alright below is basically my class with a few things changed to protect the innocent. :)

    If you decide to build a custom DLL and sell this to the public I'll expect royalties :P

    The only thing I added additional to this class was System.IO

    One thing to note is that the temp files are kept "forever" can modify as needed to make sure you don't eat space indefinitely. I just have another service I wrote that runs on the server and deletes file in folders I tell it to that are older than X days so I just made it look in this temp folder as well.

    Let me know if you have more questions.

    ######

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Sage.CRM.WebObject;
    using Sage.CRM.Utils;
    using Sage.CRM.Data;
    using System.IO;

    namespace MYDLLNAMESPACE
    {
    public class ExportData : Web
    {
    public override void BuildContents()
    {
    string hostName = Dispatch.Host;
    string installName = Dispatch.InstallName.ToLower();
    string strHttp = Dispatch.ServerVariable("HTTPS") == "off" ? "http" : "https";
    string sid = Dispatch.QueryField("SID");
    string userid = CurrentUser.UserId.ToString();

    // build where clause
    string whereclause = String.Empty;

    try
    {
    if (!String.IsNullOrEmpty(Dispatch.QueryField("comp_name")))
    {
    whereclause += whereclause == String.Empty ? "WHERE " : "AND ";
    whereclause += "comp_name like '%" + Dispatch.QueryField("comp_name") + "%' ";
    }

    if (!String.IsNullOrEmpty(Dispatch.QueryField("comp_secterr")) && Dispatch.QueryField("comp_secterr") != "0")
    {
    whereclause += whereclause == String.Empty ? "WHERE " : "AND ";
    whereclause += "comp_secterr = '" + Dispatch.QueryField("comp_secterr") + "' ";
    }

    if (!String.IsNullOrEmpty(Dispatch.QueryField("orit_productfamilyid")) && Dispatch.QueryField("orit_productfamilyid") != "null")
    {
    whereclause += whereclause == String.Empty ? "WHERE " : "AND ";
    whereclause += "orit_productfamilyid = '" + Dispatch.QueryField("orit_productfamilyid") + "' ";
    }

    if (!String.IsNullOrEmpty(Dispatch.QueryField("orit_productid")))
    {
    if (Dispatch.QueryField("orit_productid") != "null")
    {
    whereclause += whereclause == String.Empty ? "WHERE " : "AND ";
    whereclause += "orit_productid = '" + Dispatch.QueryField("orit_productid") + "'";
    }
    }

    if (!String.IsNullOrEmpty(Dispatch.QueryField("orde_contract")))
    {
    whereclause += whereclause == String.Empty ? "WHERE " : "AND ";
    string Operator = Dispatch.QueryField("orde_contract_operator");
    if (Operator == "GreaterThan")
    {
    Operator = ">";
    }
    else if (Operator == "LessThan")
    {
    Operator = "<";
    }
    else
    {
    Operator = "=";
    }
    whereclause += "orde_contract " + Operator + " '" + Dispatch.QueryField("orde_contract") + "'";
    }
    }
    catch (Exception ex)
    {
    AddError(ex.ToString());
    }

    // get data from database using known view name and the recently built where clause
    string query = "SELECT * FROM vContractViewExample " + whereclause;
    QuerySelect qry = new QuerySelect();
    qry.SQLCommand = String.Format(query);
    qry.ExecuteReader();

    // build the csv list
    // first record is column headers because I want them
    // then I loop through the actual results from the above query and add them a line at a time.
    List output = new List();
    output.Add(new string[] { "CONTRACT", "COMPANY", "OWNER", "ITEM", "MODEL", "ORIG START RENT", "PROJ RETURN" });
    while (!qry.Eof())
    {
    output.Add(new string[] { qry.FieldValue("orde_contract"), qry.FieldValue("comp_name").Replace(",", ""), qry.FieldValue("OwnerName").Replace(",", ""), qry.FieldValue("orit_item"), qry.FieldValue("prod_name"), qry.FieldValue("orit_orig_start_rent"), qry.FieldValue("orit_projret") });
    qry.Next();
    }

    try
    {
    string filename = sid + ".csv";
    string filepath;
    if (installName == "tst")
    {
    filepath = @"C:\Program Files (x86)\Sage\CRM\TST\WWWRoot\Temp\" + filename;
    }
    else
    {
    filepath = @"F:\CRM\WWWRoot\Temp\" + filename;
    }
    TextWriter writer = File.CreateText(filepath);
    for (int index = 0; index
    {
    writer.WriteLine(string.Join(",", output[index]));
    }
    writer.Close();

    string fileurl = String.Format("{0}://{1}/{2}/temp/{3}", strHttp, hostName, installName, filename);
    AddContent("");
    AddInfo("You may safely close this window after your file downloads.");
    }
    catch (Exception ex)
    {
    AddError(ex.ToString());
    }
    }
    }
    }

  • 0

    You will notice in the portion where I'm rebuilding the where clause I pull out information from the querystring that is calling this custom class. So on the other end I have a javascript method that builds that custom querystring.

  • 0

    Brad...

    It does look like I could use some help with some of the code in regards to "creating a custom class called exportdata". I have tried several options...however, I get stuck because I am wanting to use references or methods that are not available to me in the .NET Framework 2.0.

    Any assistance or examples you can provide would be greatly appreciated.

    Thanks!

  • 0

    Brad:

    Thank you! I will give this a go.

    I am customizing CRM in house for our own use...so no public creation of a .dll for sale to public. :-) I will give you credit in the code comments. //Created by: bradd a really nice guy on the Sage CRM community. Kidding, I will make it better than that in the comments.

    Now lets see if I can make this work....I will let you know. Thanks again!

  • 0

    Brad:

    Thank you for your assistance on this. However, I don't think I am going to be able to pull this off. The code made me a little dizzy (i.e. it is over my head).

    Since this was a list page, I went to an asp page and tried to use what I understand to be built in functionality for Sage CRM with this line of code....

    myBlock.AddButton(CRM.Button("Export", "list.gif","javascript:document.EntryForm.TargetAction.value = 'ExportToFile'; document.EntryForm.submit();"));

    My list displays fine and the button is there...however, when I hit the button "ExportToFile"....nothing happens. I must be missing something. If you have used this before and might know why this is not working, I would appreciate any assistance. I am going to create a new post for help with exporting to excel from an asp page. I am going to post what I have tried there.

    Thank you for your help...it is greatly appreciated.

  • 0

    The page I have the export button is actually a custom .net page, that has a list with a filter. The list and filter are defined in the system and then just drawn with the .net api.

    In the override BuildContents method I have..

    AddUrlButton("Export List", "ExportToCSV.gif", ExportListUrl());

    And the method to build the javascript action.

    I mix a little crm js api with regular jquery to build the url string by grabbing values from the filter on the screen and then setting those values in a query string.

    private string ExportListUrl()

    {

    string hostName = Dispatch.Host;

    string installName = Dispatch.InstallName.ToLower();

    string strHttp = Dispatch.ServerVariable("HTTPS") == "off" ? "http" : "https";

    string sid = Dispatch.QueryField("SID");

    string userid = CurrentUser.UserId.ToString();

    string url = String.Format("{0}://{1}/{2}/eware.dll/Do?SID={3}&Act=432&Mode=1&CLk=T&Key0=4&Key4={4}&PopupWin=Y&dotnetdll=CUSTOMDLLNAME&dotnetfunc=RunExportData", strHttp, hostName, installName, sid, userid);

    return "javascript: " +

    "var url = '" + url + "&export=yes&comp_name='+crm('comp_name').val()+'&comp_secterr='+crm('comp_secterr').val()+'&orit_productfamilyid='+crm('orit_productfamilyid').val()+'&orit_productid='+crm('orit_productid').val()+'&orde_dticket='+$('#orde_dticket').val()+'&orde_dticket_operator='+$('#SearchNumericOperatorsorde_dticket').val();" +

    "day = new Date(); id = day.getTime();" +

    "window.open(url, id, 'toolbar=0, scrollbars=0, location=0, statusbar=0, menubar=0, resizable=0, width=600, height=200, left=340, top=200');";

    }

    Notice that the dotnetfunc portion of the string is RunExportData.. this method is in the base class of my custom .net project. That method calls the ExportData class.

    public static void RunExportData(ref Web AretVal)

    {

    AretVal = new ExportData();

    }

    Hopefully this helps more.