CSDN博客

img luchuanbo

将数据从DataGridView中导出成CSV格式文件

发表于2008/9/29 15:48:00  1247人阅读

将数据从DataGridView中导出成CSV格式文件, 完整代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Statistic.BaseClass
{
    class DataExport
    {
        public static void ExportToCSV(DataGridView dgv, string fileName)
        {
            if (dgv.Rows.Count < 1)
            {
                MessageBox.Show("没有记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SaveFileDialog sfDialog = new SaveFileDialog();
            sfDialog.Filter = "CSV文件(*.csv)|*.csv|文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            sfDialog.FilterIndex = 0;
            sfDialog.FileName = fileName;
            if (sfDialog.ShowDialog() == DialogResult.OK)
            {

                string strFileName = sfDialog.FileName;
                StreamWriter sw = new StreamWriter(strFileName, false, Encoding.Unicode);
                string strLine = "";
                foreach (DataGridViewColumn col in dgv.Columns)
                {
                    if (col.Visible)
                    {
                        strLine += "/"" + col.HeaderText.Trim().Replace("/"", "///"") + "/"" + "/t";
                    }
                }
                strLine = strLine.Substring(0, strLine.Length - 1);
                sw.WriteLine(strLine);
                sw.Flush();

                foreach (DataGridViewRow dgvr in dgv.Rows)
                {
                    strLine = "";
                    foreach (DataGridViewCell dgvc in dgvr.Cells)
                    {
                        if (dgvc.Visible)
                        {
                            if (dgvc.Value == null)
                            {
                                strLine += "/t";
                            }
                            else
                            {
                                strLine += "/"" + dgvc.Value.ToString().Trim().Replace("/"","/"/"") + "/"" + "/t";
                            }
                        }
                    }
                    sw.WriteLine(strLine);
                    sw.Flush();
                }
                sw.Close();
                MessageBox.Show(string.Format("数据已成功导出至/n{0}/n文件中!", strFileName), "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

阅读全文
0 0

相关文章推荐

img
取 消
img