Solved

Ability to save datable as csv file and give it a name on a web application using asp.net c#

Posted on 2010-11-17
10
274 Views
Last Modified: 2012-05-10
I have a web application and am passing a datatable to a method which then converts this to a csv file and save to my c drive.
I want my users to be able to save this file with their own names and specify a location to save this to on their computer. Here is my code below. I am using asp.net c#
Here is how I call the method

SaveDataTableToCsvFile(@"c:\filename.csv", datatable, ",");



Here is the method:



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);

            //System.IO.StringWriter sw = new System.IO.StringWriter(); 



            //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
  • 5
  • 4
10 Comments
 
LVL 11

Expert Comment

by:jasonduan
ID: 34156988
Impossible.

The code runs on the server. It cannot write files to user's computer.
0
 
LVL 7

Accepted Solution

by:
mr_nadger earned 500 total points
ID: 34157030
a colleague has been using this

http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html

put a hidden gridview on the page, bind the table to it and off you go :)
0
 
LVL 11

Expert Comment

by:jasonduan
ID: 34157052
However, you can use the following code to "push" the file to browser, and the user can choose to where save the file and spefify filename.

response.ClearContent();
response.ClearHeaders();
response.AppendHeader( "content-disposition" , String.Format( "attachment; filename={0}" , attachmentName ) );

response.ContentType = "text/ascii"
response.Write( data );
response.End();
0
 

Author Comment

by:Sirdots
ID: 34157126
Thanks jasonduan: How do I apply the code above to the method I have? where do i put it?
0
 
LVL 11

Expert Comment

by:jasonduan
ID: 34157181
I would guess you have a button to trigger the process. The button's event handler will look like this:
protected void btnMyButton_Click(object sender, EventArgs e)
{
    // call your function to generate the file data
   string data = ......;  

   // specity the default file name
   string attachmentName = .....;  

   // send the file content to browser
   response.ClearContent();
   response.ClearHeaders();
   response.AppendHeader( "content-disposition" , String.Format( "attachment; filename={0}" ,    attachmentName ) );

   response.ContentType = "text/ascii"
   response.Write( data );
   response.End();
}
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:Sirdots
ID: 34158076
Thanks Jasonduan. You are not looking at my code below.  I know I have to call this from a button click event but where will your own code fall within my method. This is what I will like to know.

SaveDataTableToCsvFile(@"c:\filename.csv", datatable, ",");

Here is the method:


SaveDataTableToCsvFile(@"c:\filename.csv", datatable, ",");



Here is the method:



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);

            //System.IO.StringWriter sw = new System.IO.StringWriter(); 



            //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
 
LVL 11

Expert Comment

by:jasonduan
ID: 34158206
I would do the following:
1. change your method signature to:
    public static void SaveDataTableToCsvFile(StreamWriter sw, DataTable TheDataTable, params string[] Options)
  and remove line: StreamWriter sw = new StreamWriter(AbsolutePathAndFileName);
   since you don't need to create a physical file on server

2. replace the calling method with:

string data;

using(MemoryStream mem = new MemoryStream())
using (StreamWriter sw = new StreamWriter(mem))
{
      SaveDataTableToCsvFile(sw, datatable, ",");

      // convert to string
    byte[] bytes = mem.ToArray();
    int dataLength = (int)mem.Length;
    data = Encoding.UTF8.GetString(bytes, 0, dataLength);
}

// specity the default file name
string attachmentName = .....;  

// send the file content to browser
response.ClearContent();
response.ClearHeaders();
response.AppendHeader( "content-disposition" , String.Format( "attachment; filename={0}" ,    attachmentName ) );

response.ContentType = "text/ascii"
response.Write( data );
response.End();


if it is not called within a web page, replace "response" with "HttoContext.Current.Response"

Hope this helps!
0
 

Author Closing Comment

by:Sirdots
ID: 34158483
Thanks to everyone
0
 
LVL 11

Expert Comment

by:jasonduan
ID: 34158711
Hi Sirdots, just curious why my apporoach does not work?
0
 

Author Comment

by:Sirdots
ID: 34158751
I was getting a lot of errors on the lines below. I forgot to save the error message. Looks like it didnt like it. I got frustrated and decided to solve it the other way.

using(MemoryStream mem = new MemoryStream())
using (StreamWriter sw = new StreamWriter(mem))

Thanks.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this tutorial viewers will learn how to define a gradient in CSS. Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Gradient. Define the background as "linear-gradient(to right, #ee3668, black)". Ensure you …
In this tutorial viewers will learn how to position overlapping items using z-index in CSS. They will also learn the restrictions on the z-index property.  Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Red.…

760 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now