CSV输出的代码

2015-04-04 21:17:07  访问(2876) 赞(0) 踩(0)


        /// <summary>
        /// 最大数字
        /// </summary>
        private const int CSV_MAX_LEN = 11;

        /// <summary>
        /// 是否是数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        protected bool CSVCellIsNumber(string str)
        {
            if (str == null)
                return false;

            int iLen = str.Length;

            if (iLen == 0)
                return false;

            int startIndex = 0;

            if (str[0] == '-')
                startIndex = 1;

            if (startIndex == iLen)
                return false;

            bool containsPoint = false;

            for (int i = startIndex; i < iLen; ++i)
            {
                if (str[i] >= '0' && str[i] <= '9')
                    continue;

                if (str[i] == '.')
                {
                    if (containsPoint)
                        return false;

                    containsPoint = true;

                    continue;
                }

                return false;
            }

            return true;
        }

        /// <summary>
        /// 是否转换
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        protected bool CSVCellNumberIsConvert(string str)
        {
            if (str == null)
                return false;

            int iLen = str.Length;

            if (iLen == 0)
                return false;

            int startIndex = 0;

            if (str[0] == '-')
                startIndex = 1;

            if (startIndex == iLen)
                return false;

            int idx = str.IndexOf('.');

            string subStr = "";

            if (idx == -1)
            {
                if (startIndex == 0)
                    subStr = str;
                else
                    subStr = str.Substring(1);
            }
            else
            {
                subStr = str.Substring(startIndex, idx);
            }

            if (subStr.Length <= CSV_MAX_LEN)
                return false;
            else
                return true;
        }

        /// <summary>
        /// CSV转义
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        protected string CSVCellConvert(string text)
        {
            if (text == null || text.Length==0 )
                return "";

            bool isNumberValue = CSVCellIsNumber(text);

            if (isNumberValue)
            {
                bool isConvert = CSVCellNumberIsConvert(text);

                if (isConvert)
                    return "\"" + '\t' + text + "\"";
                else
                    return text;
            }



            if (text.Contains("\""))
            {
                text = text.Replace("\"", "\"\"");
                return "\"" + text + "\"";
            }

            if (text.Contains(","))
            {
                return "\"" + text + "\"";
            }
            return text;
        }


        /// <summary>
        /// 导出Excel模式
        /// </summary>
        /// <param name="lv"></param>
        /// <param name="fileName"></param>
        public void CSVExportTo
            (
                string fileName,
                List<List<string>> theList
            )
        {
            if (theList == null || theList.Count == 0)
                return;

            StringBuilder theResult = new StringBuilder();

            int iCount = 0;

            foreach (List<string> sonList in theList)
            {
                if(sonList==null)
                    continue;

                iCount = sonList.Count;

                if (iCount == 0)
                    continue;

                theResult.Append(CSVCellConvert(sonList[0]));

                for (int i = 1; i < iCount; ++i)
                {
                    theResult.Append(",");
                    theResult.Append(CSVCellConvert(sonList[i]));
                }

                theResult.AppendLine();
            }

            CSVWriteFile
                (
                    fileName,
                    theResult.ToString(),
                    Encoding.GetEncoding("gb2312"),
                    true,
                    false
                );

        }



        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="textValue"></param>
        /// <param name="textEncoding"></param>
        /// <param name="IsOverwrite"></param>
        /// <param name="IsAppend"></param>
        protected   void CSVWriteFile
            (
                string fileName,
                string textValue,
                System.Text.Encoding textEncoding,
                bool IsOverwrite,
                bool IsAppend
            )
        {
            if (fileName == null || fileName.Length == 0)
            {

                throw new Exception
                    (
                        "方法:"
                        + MethodBase.GetCurrentMethod().ReflectedType.FullName
                        + " "
                        + MethodBase.GetCurrentMethod().ToString()
                        + " 发生异常:"
                        + "传入的字符串参数:fileName为null或为空。"
                    );
            }

            FileInfo info = new FileInfo(fileName);

            if (info.Exists)
            {
                // 文件存在,且不覆盖 //
                if (!IsOverwrite)
                {

                    throw new Exception
                        (
                            "方法:"
                            + MethodBase.GetCurrentMethod().ReflectedType.FullName
                            + " "
                            + MethodBase.GetCurrentMethod().ToString()
                            + " 发生异常:文件" + info.FullName + "已存在,并且不允许覆盖。"
                        );
                }

                // 如果不是追加 //
                if (!IsAppend)
                    File.Delete(info.FullName);
            }
            else
            {
                // 创建目录 //
                if (!info.Directory.Exists)
                {
                    Directory.CreateDirectory(info.Directory.FullName);
                }
            }


            FileStream fs = null;

            StreamWriter m_streamWriter = null;

            try
            {
                //创建一个文件流,用以写入或者创建一个StreamWriter
                fs = new FileStream(info.FullName, FileMode.OpenOrCreate, FileAccess.Write);

                if (textEncoding == null)
                {
                    m_streamWriter = new StreamWriter(fs);
                }
                else
                {
                    m_streamWriter = new StreamWriter(fs, textEncoding);
                }

                m_streamWriter.Flush();

                //  使用StreamWriter来往文件中写入内容
                if (IsAppend)
                    m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);

                m_streamWriter.Write(textValue);
                m_streamWriter.Flush();
            }
            catch (Exception err)
            {
                throw err;
            }
            finally
            {
                if (m_streamWriter != null)
                {
                    m_streamWriter.Flush();
                    m_streamWriter.Close();
                }

                if (fs != null)
                {
                    fs.Close();
                }

                m_streamWriter = null;

                fs = null;
            }
        }


标签:CSV输出的代码 

上一条:

下一条:


版权声明:
如果本站的资源使用了您的作品,请联系我们,我们会及时的注明
本站所有的资源均为免费自由下载,目的是让大家学习和交流
由于收集过程中几经转载,所以很多作品的原作者不详
如果您不愿在本站展示,请联系我们,我们会及时删除
 

相关评论

评论加载中……
 

发表评论

类型:
内容:
  (Alt+Enter)
 
  ┈全部┈  
 
(显示默认分类)