Csharp: datagridview Convert csv file, csharpdatagridview

Source: Internet
Author: User

Csharp: datagridview Convert csv file, csharpdatagridview

/// <summary>
        /// save document
        /// Tu Juwen
        /// 2014-08-29
        /// Geovin Du
        /// </ summary>
        /// <param name = "dGV"> </ param>
        /// <param name = "filename"> </ param>
        public static void DataGridViewToCsV (DataGridView dGV, string filename)
        {

            string stOutput = "";
            // Export titles:
            string sHeaders = "";
            for (int j = 0; j <dGV.Columns.Count; j ++)

                sHeaders = sHeaders.ToString () + Convert.ToString (dGV.Columns [j] .HeaderText) + ",";
            stOutput + = sHeaders + "\ r \ n";
            // Export data.
            for (int i = 0; i <dGV.RowCount-1; i ++)
            {

                string stLine = "";
                for (int j = 0; j <dGV.Rows [i] .Cells.Count; j ++)
                    stLine = stLine.ToString () + Convert.ToString (dGV.Rows [i] .Cells [j] .Value) + ",";
                stOutput + = stLine + "\ r \ n";

            }
            UTF8Encoding utf8 = new UTF8Encoding ();
            string file = "1.csv";
            SaveFileDialog saveFileDialog1 = new SaveFileDialog ();
            saveFileDialog1.InitialDirectory = Environment.GetFolderPath (Environment.SpecialFolder.Desktop); //Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            saveFileDialog1.CreatePrompt = true;
            saveFileDialog1.OverwritePrompt = true;
            saveFileDialog1.Title = "Save text Files";
            //saveFileDialog1.CheckFileExists = true;
            //saveFileDialog1.CheckPathExists = true;
            saveFileDialog1.DefaultExt = "csv";
            saveFileDialog1.Filter = "csv files (* .csv) | * .csv | All files (*. *) | *. *";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.RestoreDirectory = true;
            System.IO.Stream fileStream;
            if (saveFileDialog1.ShowDialog () == DialogResult.OK)
            {
                // FileStream fs = new FileStream (filename, FileMode.Create);
                file = saveFileDialog1.FileName;
                fileStream = saveFileDialog1.OpenFile ();
                MemoryStream userInput = new MemoryStream ();
                byte [] output = Encoding.Default.GetBytes (stOutput);
                //fileStream.Read(output, 0, (int) output.Length);
                fileStream.Write (output, 0, output.Length);
                fileStream.Close ();

            }


        }
        /// <summary>
        /// save document
        /// Tu Juwen
        /// 2014-08-28
        /// Geovin Du
        /// </ summary>
        /// <param name = "dGV"> </ param>
        /// <param name = "filename"> </ param>
        public static void DataGridViewToCsVDu (DataGridView dGV, string filename)
        {

            string stOutput = "";

            // Export titles:
            string sHeaders = "";
            for (int j = 0; j <dGV.Columns.Count; j ++)

                sHeaders = sHeaders.ToString () + Convert.ToString (dGV.Columns [j] .HeaderText) + ",";
            stOutput + = sHeaders + "\ r \ n";
            // Export data.
            for (int i = 0; i <dGV.RowCount-1; i ++)
            {

                string stLine = "";

                for (int j = 0; j <dGV.Rows [i] .Cells.Count; j ++)

                    stLine = stLine.ToString () + Convert.ToString (dGV.Rows [i] .Cells [j] .Value) + ",";

                stOutput + = stLine + "\ r \ n";

            }
            UTF8Encoding utf8 = new UTF8Encoding ();
            // Encoding utf16 = Encoding.GetEncoding (1200); // unicode encoding
            byte [] output = Encoding.Default.GetBytes (stOutput);
            FileStream fs = new FileStream (filename, FileMode.Create);
            BinaryWriter bw = new BinaryWriter (fs, Encoding.Default);
            bw.Write (output, 0, output.Length); // write the encoded file
            bw.Flush ();
            bw.Close ();
            fs.Close ();
            

        } 

 


How to import the data in the csv file to the dview in C #

Csv data can be directly written using the openText of I/O. All data can be read in simplified format. The key is line breaks.

Who has the C # datagridview export csv excel Code?

// I downloaded this code from the Internet
// The main meaning of this Code is to determine whether the exported file already exists. If the file already exists, delete it.
// Open the file StreamWriter sw = new StreamWriter (new FileStream (strPath, ileMode. CreateNew), Encoding. GetEncoding ("GB2312 "));
The field name is written to the file.
// Write data cyclically at Layer 2
// Note that the field delimiter is ","
// Close the file.
Using System;
Using System. Collections. Generic;
Using System. IO;
Using System. Text;
Using System. Data;

Namespace Utility
{
Public class CSVHelper
{
// Export the file as svc, and strFileName is the path and file name of the csv file to be exported: for example, "d: est est.csv"
Public void ExportToSvc (System. Data. DataTable dt, string strFileName)
{
String strPath = strFileName;
If (File. Exists (strPath ))
{
File. Delete (strPath );
} // Delete the object if it already exists
// Print the header first
StringBuilder strColu = new StringBuilder ();
StringBuilder strValue = new StringBuilder ();
Int I = 0;
Try
{
StreamWriter sw = new StreamWriter (new FileStream (strPath, FileMode. CreateNew), Encoding. GetEncoding ("GB2312 "));

For (I = 0; I <= dt. Columns. Count-1; I ++)
{
StrColu. Append (dt. Columns. ColumnName );
StrColu. Append (","); // The csv separator is ","
}
StrColu. Remove (strColu. Length-1, 1); // Remove the last character

... The remaining full text>
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.