4

How to Create a .CSV file from the reading the database in asp.net?Can any one suggest me how to create the .CSV file in asp.net?

Thanks in Advance.

Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75
Vikas
  • 368
  • 2
  • 3
  • 8

6 Answers6

5

Check this: Exporting DataTable to CSV File Format

public void CreateCSVFile(DataTable dt, string strFilePath)    
    {    
        #region Export Grid to CSV     

        // Create the CSV file to which grid data will be exported.    
        StreamWriter sw = new StreamWriter(strFilePath, false);

        // First we will write the headers.    
        //DataTable dt = m_dsProducts.Tables[0];    
        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);

        // Now write all the rows.    
        foreach (DataRow dr in dt.Rows)    
        {    
            for (int i = 0; i < iColCount; i++)    
            {    
                if (!Convert.IsDBNull(dr[i]))    
                {    
                    sw.Write(dr[i].ToString());    
                }    
                if (i < iColCount - 1)    
                {    
                    sw.Write(",");    
                }    
            }    
            sw.Write(sw.NewLine);    
        }    
        sw.Close(); 

        #endregion    
    }

If you are trying to force the download to always give a Save As, you should set the content-type to application/octet-stream.

Source:

 string attachment = "attachment; filename=MyCsvLol.csv";
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.AddHeader("content-disposition", attachment);
    HttpContext.Current.Response.ContentType = "text/csv";
    HttpContext.Current.Response.AddHeader("Pragma", "public");

    var sb = new StringBuilder();
    foreach(var line in DataToExportToCSV)
      sb.AppendLine(TransformDataLineIntoCsv(line));

    HttpContext.Current.Response.Write(sb.ToString());
    HttpContext.Current.Response.End();

One of the simplest is using FileHelpers Library

FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);

WriteFile (inherited from FileHelperEngine) Overloaded. Write an array of records to the specified file.

WriteStream (inherited fromFileHelperEngine) Overloaded. Write an array of records to the specified Stream.

WriteString (inherited from FileHelperEngine) Overloaded. Write an array of records to an String and return it.

Reference:
Write to CSV file and export it?
Export Data to a Comma Delimited (CSV) File for an Application Like Excel
export datatable to CSV with Save File Dialog box - C#

Ortund
  • 8,095
  • 18
  • 71
  • 139
Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75
  • 4
    Your code to write the CSV file is incomplete. If a field contains a comma, it will not be parsed correctly by programs like Excel. – Jonathan Wood Nov 16 '12 at 05:25
  • @JonathanWood: I have not tested the code completly and may be you better know that stackoverflow is not code provider side. the purpose of this website to help not do all the work of others. the specified reference is enough to guide him to solve their problem. – Niranjan Singh Nov 16 '12 at 05:32
  • Please see my stackoverflow score and you'll probably see that I do know what stackoverflow is about. Yes, I think your answer was helpful. But it was incomplete and the OP may not realize that. Depending on his data, it might in fact not be enough to solve their problem. That's why I pointed it out. – Jonathan Wood Nov 16 '12 at 05:35
  • @JonathanWood: Well thanks for the suggestion. I pointed that link in reference because that was belong to `asp.net website and also have video tutorial`. – Niranjan Singh Nov 16 '12 at 06:06
0

You can see how to create a CSV file in the article Reading and Writing CSV Files in C#.

You can see how to dynamically generate the file content but have it behave like a downloadable file in the article Creating Downloadable Content Dynamically.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • 1
    Sounds way too complicated ... and you still need to set "response.ContentType()" for the user to be prompted to "Save" the .csv returned by the web server. IMHO... – paulsm4 Nov 16 '12 at 05:25
  • Which part was too complicated? Did you see that the second article did set `Response.ContentType`? (BTW, the second article mentioned seems to basically be what you suggested in your answer. But the first has a more complete implementation of CSV handling.) – Jonathan Wood Nov 16 '12 at 05:28
0

Why can't you just:

1) Query the database (e.g. with a SQL reader),

2) set your HTTP response header (response.ContentType) to the MIME type "application/csv"

3) write out (response.Write) each line of your result set in comma-delimited (CSV) format?

Here's an example of exactly that approach:

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
0

Try this:

string filePath = @"C:\test.csv";  
string delimiter = ",";  

string[][] output = new string[][]{  
new string[]{"Col 1 Row 1", "Col 2 Row 1", "Col 3 Row 1"},  
new string[]{"Col1 Row 2", "Col2 Row 2", "Col3 Row 2"}  
};  
int length = output.GetLength(0);  
StringBuilder sb = new StringBuilder();  
for (int index = 0; index < length; index++)  
sb.AppendLine(string.Join(delimiter, output[index]));  

File.WriteAllText(filePath, sb.ToString()); 

for more Help.

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0

Anyway, you should find any robust CSV library for this, if you allow special characters like double quote, comma, space, etc... to appear in your file.

linquize
  • 19,828
  • 10
  • 59
  • 83
0

Think that you are looking for the format of CSV file. It's really a normal text file that has very simple structure. You can refer Wiki here.

You can make it by yourself by getting data from your database & write the data to a text file as your need.

Here is an example of content of a CSV file:

Year,Make,Model
1997,Ford,E350
2000,Mercury,Cougar

There are 3 columns: Year, Make, Model in the file and 2 row of data are: 1997,Ford,E350, 2000,Mercury,Cougar.

Han
  • 3,272
  • 3
  • 24
  • 39