简体   繁体   中英

Export to .csv from html

I want to export a table in my html page to a .csv file. I can use something like:

private void GenerateExcelFileOnType(string filePath1, ref DataTable dt)
        {
            if (dt != null)
            {
                string line = string.Empty;
                if (dt.Rows.Count > 0)
                {
                    string str = dt.ToCSV();
                    using (StreamWriter sw = new StreamWriter(filePath1))
                    {
                        sw.Write(str);
                    }
                }
                dt.Clear();
                dt = null;
            }
        }

But is there any way with which I can directly export from the html page, like we do a print (windows.print)

As far as I'm aware there's no reliable way of initiating a downloadable file straight from a web page, other than sending another HTTP Request and responding with a downloadable mime-type.

I can't really see a great need for one either. So long as you can send a request with the various information needed, your server can respond appropriately.

Update

It seems, from your comments, that you aren't looking to actually write to a CSV file locally. If you just want to display the CSV as text within the browser, then of course this is possible, with some simple iteration:

function csv(id){

  var output = '';

  $('table#' + id + ' tr').each(function(i){

    if(i)
      output += '</br>';

    var children = $(this).find('td, th');

    children.each(function(j){

      output += '\"' + $(this).html() +  '\"';

      if(j < children.length - 1)
        output += ', ';

    });
  });

  return output;

}

Here's a fiddle ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM