Vikas
Vikas

Reputation: 376

How to create a .csv file in asp.net?

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.

Upvotes: 4

Views: 16810

Answers (6)

Niranjan Singh
Niranjan Singh

Reputation: 18290

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#

Upvotes: 5

Han
Han

Reputation: 3334

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.

Upvotes: 0

linquize
linquize

Reputation: 20396

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.

Upvotes: 0

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28578

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.

Upvotes: 0

paulsm4
paulsm4

Reputation: 121799

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:

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67273

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.

Upvotes: 0

Related Questions