using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

namespace CRVM
{
    class ExportToCSV
    {
        private string _filePath;
        private bool _writeOK = false;
        private StreamWriter writer;

        public bool writeOK
        {
            get
            {
                return _writeOK;
            }
        }

        public ExportToCSV(string filepath)
        {
            this._filePath = filepath;
        }

        public void writeProductData(DataTable data)
        {
            try
            {
                writer = new StreamWriter(new FileStream(_filePath, FileMode.OpenOrCreate), Encoding.Default);
                string line = "";
                for (int i = 0; i < data.Columns.Count; i++)//打印表头
                {
                    //if (i != data.Columns.Count - 2)
                    {
                        line += data.Columns[i].ColumnName;
                        if (i != data.Columns.Count - 1)
                        {
                            line = line + ",";
                        }
                    }
                }
                writer.WriteLine(line);

                for (int i = 0; i < data.Rows.Count; i++)
                {
                    line = "";
                    for (int j = 0; j < data.Columns.Count; j++)
                    {
                        //if (j != data.Columns.Count - 2)//status列不打印
                        {
                            line = line + data.Rows[i][j].ToString().Trim();
                            if (j != data.Columns.Count - 1)
                            {
                                line = line + ",";
                            }
                        }
                    }
                    writer.WriteLine(line);
                }
                _writeOK = true;
            }
            catch (Exception ex)
            {
                _writeOK = false;
            }
            finally
            {
                writer.Close();
            }
        }

        public string EncodingCovert(Encoding src, Encoding dest, string text)
        {
            var bytes = src.GetBytes(text);
            bytes = Encoding.Convert(src, dest, bytes);
            return dest.GetString(bytes);
        }
    }
}
