首页 > 代码库 > CSVHelper 导出CSV 格式

CSVHelper 导出CSV 格式

public class CSVHelper
    {
        System.Windows.Forms.SaveFileDialog saveFileDialog1;//保存
        private string header = string.Empty;//标题

        /// <summary>
        /// 初始化打印设置
        /// </summary>
        /// <param name="printID"></param>
        protected void InitExportController(Dictionary<string, object> addition)
        {
            saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();

            saveFileDialog1.Filter = "导出CSV (*.csv)|*.csv";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.CreatePrompt = false;
            saveFileDialog1.Title = "导出文件保存路径";
            saveFileDialog1.RestoreDirectory = true;//保存对话框是否记忆上次打开的目录 

            header = addition["HeardTitle"].ToString();
            saveFileDialog1.FileName = header;
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="dt">表格</param>
        /// <param name="strFileName">路径</param>
        public bool Export(Dictionary<string, object> addition, System.Data.DataTable dt)
        {
            if (!object.Equals(dt, null))
            {
                InitExportController(addition);
                try
                {
                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        string filename = saveFileDialog1.FileName;
                        return ExportToSvc(addition, dt, filename);
                    }
                }
                catch
                {
                    saveFileDialog1.FileName = "请输入文件名称";
                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        string filename = saveFileDialog1.FileName;
                        return ExportToSvc(addition, dt, filename);
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="gv">内容</param>
        /// <param name="strFileName">路径</param>
        public bool Export(Dictionary<string, object> addition, DataGridView gv)
        {
            if (gv.Rows.Count > 0)
            {
                InitExportController(addition);

                try
                {
                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        string filename = saveFileDialog1.FileName;
                        return ExportToSvc(addition, gv, filename);
                    }
                }
                catch
                {
                    saveFileDialog1.FileName = "请输入文件名称";
                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        string filename = saveFileDialog1.FileName;
                        return ExportToSvc(addition, gv, filename);
                    }
                }
            }
            return false;
        }


        /// <summary>
        /// 导出为svc文件,strFileName为要导出的csv格式文件的路径和文件名
        /// </summary>
        /// <param name="addition">头部信息</param>
        /// <param name="dt">表格</param>
        /// <param name="strFileName">路径</param>
        protected bool ExportToSvc(Dictionary<string, object> addition, System.Data.DataTable dt, string strFileName)
        {
            string strPath = strFileName;
            if (File.Exists(strPath))
            {
                File.Delete(strPath);
            }

            //先打印标头
            StringBuilder strColu = new StringBuilder();
            StringBuilder strValue = new StringBuilder();
            int i = 0;
            try
            {
                StreamWriter sw = new StreamWriter(new FileStream(strPath, FileMode.CreateNew), Encoding.GetEncoding("GB2312"));
                if (addition.ContainsKey("HeardTitle"))
                {
                    sw.WriteLine(addition["HeardTitle"].ToString());
                }

                if (addition.ContainsKey("Content"))
                {
                    sw.WriteLine(addition["Content"].ToString());
                    sw.WriteLine();
                }


                for (i = 0; i <= dt.Columns.Count - 1; i++)
                {
                    if (addition.ContainsKey(dt.Columns[i].ColumnName))
                    {
                        strColu.Append(addition[dt.Columns[i].ColumnName].ToString().Trim());
                    }
                    else
                    {
                        strColu.Append(dt.Columns[i].ColumnName);
                    }
                    strColu.Append(",");
                }
                strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符

                sw.WriteLine(strColu);

                foreach (DataRow dr in dt.Rows)
                {
                    strValue.Remove(0, strValue.Length);//移出

                    for (i = 0; i <= dt.Columns.Count - 1; i++)
                    {
                        strValue.Append(dr[i].ToString());
                        strValue.Append(",");
                    }
                    strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
                    sw.WriteLine(strValue);
                }
                if (addition.ContainsKey("Foot"))
                {
                    sw.WriteLine();
                    sw.WriteLine(addition["Foot"].ToString());
                }
                sw.Close();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 导出为svc文件,strFileName为要导出的csv格式文件的路径和文件名
        /// </summary>
        ///  <param name="addition">头部信息</param>
        /// <param name="gv">DataGridView控件</param>
        /// <param name="strFileName"></param>
        protected bool ExportToSvc(Dictionary<string, object> addition, DataGridView gv, string strFileName)
        {
            string strPath = strFileName;
            if (File.Exists(strPath))
            {
                File.Delete(strPath);
            }

            //先打印标头
            StringBuilder strColu = new StringBuilder();
            StringBuilder strValue = new StringBuilder();
            int i = 0;
            try
            {
                StreamWriter sw = new StreamWriter(new FileStream(strPath, FileMode.CreateNew), Encoding.GetEncoding("GB2312"));

                if (addition.ContainsKey("HeardTitle"))
                {
                    sw.WriteLine(addition["HeardTitle"].ToString());
                }

                if (addition.ContainsKey("Content"))
                {
                    sw.WriteLine(addition["Content"].ToString());
                    sw.WriteLine();
                }

                for (i = 0; i <= gv.Columns.Count - 1; i++)
                {
                    if (gv.Columns[i].Visible == true)
                    {//可见的列导出,隐藏的列过滤
                        strColu.Append(gv.Columns[i].HeaderText.Trim());
                        strColu.Append(",");
                    }
                }
                strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符
                sw.WriteLine(strColu);

                foreach (DataGridViewRow dr in gv.Rows)
                {
                    strValue.Remove(0, strValue.Length);//移出

                    for (i = 0; i <= gv.Columns.Count - 1; i++)
                    {
                        if (gv.Columns[i].Visible == true)
                        {//可见的导出
                            strValue.Append(dr.Cells[i].Value.ToString());
                            strValue.Append(",");
                        }
                    }
                    strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
                    sw.WriteLine(strValue);
                }

                if (addition.ContainsKey("Foot"))
                {
                    sw.WriteLine();
                    sw.WriteLine(addition["Foot"].ToString());
                }

                sw.Close();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 导出CSV
        /// </summary>
        /// <param name="title">显示标题</param>
        /// <param name="name">文件名</param>
        /// <param name="dts">一至多个表源</param>
        /// <returns></returns>
        public bool Export(string title, string name, params DataTable[] dts)
        {
            bool result = false;
            if (dts != null && dts.Length > 0)
            {
                var dict = new Dictionary<string, object>();
                dict["HeardTitle"] = name;
                InitExportController(dict);
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        using (StreamWriter sw = new StreamWriter(new FileStream(saveFileDialog1.FileName, FileMode.CreateNew), Encoding.GetEncoding("GB2312")))
                        {
                            sw.WriteLine(title);
                            foreach (DataTable dt in dts)
                            {
                                StringBuilder strValue = new StringBuilder();
                                StringBuilder strColu = new StringBuilder();
                                for (int i = 0; i <= dt.Columns.Count - 1; i++)
                                {
                                    strColu.Append(dt.Columns[i].ColumnName);
                                    strColu.Append(",");
                                }
                                strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符

                                sw.WriteLine(strColu);

                                foreach (DataRow dr in dt.Rows)
                                {
                                    strValue.Remove(0, strValue.Length);//移出

                                    for (int i = 0; i <= dt.Columns.Count - 1; i++)
                                    {
                                        strValue.Append(dr[i].ToString());
                                        strValue.Append(",");
                                    }
                                    strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
                                    sw.WriteLine(strValue);
                                }
                                sw.WriteLine();
                            }
                        }
                        result = true;
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine(exc.Message);
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 导出CSV
        /// </summary>
        /// <param name="title">显示标题</param>
        /// <param name="name">文件名</param>
        /// <param name="dts">一至多个表源</param>
        /// <returns></returns>
        public bool Export(string title, string name, DataSet ds)
        {
            bool result = false;
            if (ds != null && ds.Tables.Count > 0)
            {
                var dict = new Dictionary<string, object>();
                dict["HeardTitle"] = name;
                InitExportController(dict);
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        using (StreamWriter sw = new StreamWriter(new FileStream(saveFileDialog1.FileName, FileMode.CreateNew), Encoding.GetEncoding("GB2312")))
                        {
                            sw.WriteLine(title);
                            foreach (DataTable dt in ds.Tables)
                            {
                                StringBuilder strValue = new StringBuilder();
                                StringBuilder strColu = new StringBuilder();
                                for (int i = 0; i <= dt.Columns.Count - 1; i++)
                                {
                                    strColu.Append(dt.Columns[i].ColumnName);
                                    strColu.Append(",");
                                }
                                strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符

                                sw.WriteLine(strColu);

                                foreach (DataRow dr in dt.Rows)
                                {
                                    strValue.Remove(0, strValue.Length);//移出

                                    for (int i = 0; i <= dt.Columns.Count - 1; i++)
                                    {
                                        strValue.Append(dr[i].ToString());
                                        strValue.Append(",");
                                    }
                                    strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
                                    sw.WriteLine(strValue);
                                }
                                sw.WriteLine();
                            }
                        }
                        result = true;
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine(exc.Message);
                    }
                }
            }
            return result;
        }
    }