Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Convert datatable to excel or csv file and save to client computer(asp.net application)

Posted on 2010-09-14
3
Medium Priority
?
740 Views
Last Modified: 2012-05-10
On the click of a button I pass a datatable to a method to generate an excel file.
Since this is a web application I want to be able to use a file dialog to save the file
locally to my computer.

how can i acheive this pls ?




/// <summary>
    /// The click of this button will convert the datatable to csv format and save in the c:\directory
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnExcel_Click(object sender, EventArgs e)
    {
        SaveDataTableToCsvFile(@"c:\sample.csv", dtg, ",");
    }


    public static void SaveDataTableToCsvFile(string AbsolutePathAndFileName, DataTable TheDataTable, params string[] Options)
    {

        try
        {
            //variables
            string separator;
            if (Options.Length > 0)
            {
                separator = Options[0];
            }
            else
            {
                separator = ","; //default
            }
            string quote = "\"";

            //create CSV file
            StreamWriter sw = new StreamWriter(AbsolutePathAndFileName);
           
            //write header line
            int iColCount = TheDataTable.Columns.Count;
            for (int i = 0; i < iColCount; i++)
            {
                sw.Write(TheDataTable.Columns[i]);
                if (i < iColCount - 1)
                {
                    sw.Write(separator);
                }
            }
            sw.Write(sw.NewLine);

            //write rows
            foreach (DataRow dr in TheDataTable.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        string data = dr[i].ToString();
                        data = data.Replace("\"", "\\\"");
                        sw.Write(quote + data + quote);
                    }
                    if (i < iColCount - 1)
                    {
                        sw.Write(separator);
                    }
                }
                sw.Write(sw.NewLine);
            }
            sw.Close();
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message);
        }
    }

Open in new window

0
Comment
Question by:Sirdots
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 33679030
Since the code you have will be executed on the SERVER, not on the client, you may have a bit of a problem.  

Generally, web apps do not have WRITE permission on the client - that would be a serious security hole.

AW
0
 
LVL 42

Accepted Solution

by:
Meir Rivkin earned 1500 total points
ID: 33679811
attached is a function which exports datatable to csv.

to enable saving it on the local computer you can stream the csv file to the client browser:

HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader( "content-disposition","attachment;
filename=" + <filename>);
HttpContext.Current.Response.BinaryWrite(File.ReadAllBytes(<filename>));
HttpContext.Current.Response.End();

<filename> - csv file path


http://dotnetguts.blogspot.com/2007/01/exporting-datatable-to-csv-file-format.html
http://www.velocityreviews.com/forums/t92977-csv-file-download-from-an-asp-net-page-issue.html
public static void ExportToCSV(DataTable dt, string strFilePath, string fileName)
        {
            var sw = new StreamWriter(strFilePath + fileName, false);

            // Write the headers.
            int iColCount = dt.Columns.Count;
            for (int i = 0; i < iColCount; i++)
            {
                sw.Write(dt.Columns[i]);
                if (i < iColCount - 1) sw.Write(",");
            }

            sw.Write(sw.NewLine);

            // Write rows.
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        if (dr[i].ToString().StartsWith("0"))
                        {
                            sw.Write(@"=""" + dr[i] + @"""");
                        }
                        else
                        {
                            sw.Write(dr[i].ToString());
                        }
                    }

                    if (i < iColCount - 1) sw.Write(",");
                }
                sw.Write(sw.NewLine);
            }

            sw.Close();
        }

Open in new window

0
 

Author Closing Comment

by:Sirdots
ID: 33855368
The file dialog was not shown here
0

Featured Post

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

609 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question