csharp: datagridview Convert csv file

 /// <summary>
        /// 保存文件
        /// 涂聚文
        /// 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>
        /// 保存文件
        /// 涂聚文
        /// 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();

        }
时间: 2024-12-11 09:57:39

csharp: datagridview Convert csv file的相关文章

C# - CSV file reader

// -------------------------------------------------------------------------------------------------------------------- // <summary> // Defines the CSVFileReader type. // </summary> // ----------------------------------------------------------

a helper class for generating xls or csv file

using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.Office.Interop.Excel; namespace Reuters.ProcessQuality.ContentAuto.Lib{ public class XlsOrCsvUtil { /// <summary> /// Generate Xls Or Csv File /// <

解决Jmeter Non GUI运行时报“...ensure the jmeter .save.saveservice.* properties are the same as when the CSV file was created or the file may be read incorrectly”错误的问题

错误信息: File 'xxx.jtl' does not contain the field names header, ensure the jmeter.save.saveservice.* properties are the same as when the CSV file was created orthe file may be read incorrectly 解决: jmeter.properties配置文件 jmeter.save.saveservice.output_fo

[PowerShell Utils] Create a list of virtual machines based on configuration read from a CSV file in Hyper-V

Hello everyone, this is the third post of the series. .   Background =============== In my solution, I have 15 Windows hosts. I need to configure them from the OS installation to configure fail over cluster and then create and run VMs on them. Withou

How to handle csv file using python

As i need to read something from a csv file using python.  I got something and put it here. Module: csv import csv FILE_FULL_PATH = 'D:\\Work\\script\\My Script\\Book1.csv' def f(): with open(FILE_FULL_PATH,'rb') as csvfile: for row in csv.reader(csv

Powercli随笔 - PowerCLI script to sequentially Storage vMotion VMs from a CSV File

PowerCLI script to sequentially Storage vMotion VMs from a CSV File This is a PowerCLI script that I use to Storage vMotion (s/vmotion) VMs from an input file (CSV File). This helps me evacuate VMs from a datastore that will be decommissioned and thi

SQL Script for select data from ebs and make a csv file to FTP

DECLARE CURSOR cur_lcy_test IS SELECT rcta.customer_trx_id, rcta.trx_number, rcta.trx_date FROM ra_customer_trx_all rcta WHERE rcta.customer_trx_id = 11993; -- rec_lcy_test cur_lcy_test%ROWTYPE; -- w_csv_line_num NUMBER := 0; TYPE tbl_varchar2 IS TAB

Csharp--Read Csv file to DataTable

在网上找的资料都不怎么好使,许多代码一看就知道根本没有考虑全面. 最后找到一个好用的,在codeplex上,这位老兄写成了一个framework,太重了. http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader 确实挺好用的. 我没耐下性子看他的实现,自己尝试写了如下的代码来完成了阅读csv. 参照:http://msdn.microsoft.com/en-us/library/ae5bf541%28v=vs.90%29.aspx 只

SQL Script for read information from a csv file in FTP Server

DECLARE w_file_path VARCHAR2(4000) := 'XXIF_INPUT'; --all_directories.directory_name w_file_name VARCHAR2(4000) := 'lcytest001.csv'; --The file name w_file_exists BOOLEAN; w_file_length NUMBER(10) DEFAULT 0; w_file_type utl_file.file_type; w_line VAR