C# 导出导入TXT文件

导出TXT关键类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Globalization;
using System.Windows.Forms;

namespace Demo
{
    /// <summary>
    /// 导出TXT
    /// 罗旭成
    /// 2014-4-15
    /// </summary>
    public class ExportTxt
    {

        #region * 将DataTable指定的列,导出到TXT文件.
        /// <summary>
        /// 将DataTable指定的列,导出到TXT文件.
        /// </summary>
        /// <param name="pDataTable">数据源表</param>
        /// <param name="pColName">列名</param>
        /// <param name="pColCaption">标题(未指定则使用列名)</param>
        /// <param name="pFilePath">完整的路径和文件名</param>
        public static void UTF8_SaveToTXT(DataTable pDataTable, string pColName, string pColCaption, string pFilePath)
        {
            //如果文件存在则删除
            if (File.Exists(pFilePath))
            {
                File.Delete(pFilePath);
            }
            //********************************************************************************************
            using (FileStream stream = new FileStream(pFilePath, FileMode.Create, FileAccess.Write))
            {
                using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                {
                    //------
                    if ((pColName == null) || (pColName.Trim() == "")) { return; }
                    if (pColCaption == null) { pColCaption = ""; }
                    String[] xColArray = pColName.Split(new Char[] { ',' });
                    String[] xColCapArray = pColCaption.Split(new Char[] { ',' });
                    for (int xI = 0, xN = xColArray.Length; xI < xN; xI++)
                    {
                        xColArray.SetValue(xColArray[xI].Trim(), xI);
                    }
                    for (int xI = 0, xN = xColCapArray.Length; xI < xN; xI++)
                    {
                        xColCapArray.SetValue(xColCapArray[xI].Trim(), xI);
                    }
                    //--*************************************************************************************************
                    //--如果标题不为空
                    if (pColCaption.Trim() != "")
                    {
                        if (xColArray.Length == xColCapArray.Length)//标题和列名的数量必须相同
                        {
                            int x = 0;
                            Boolean xFind = false;
                            for (int j = 1; j < xColArray.Length; j++)
                            {
                                //设计列名
                                for (int i = 0; i < pDataTable.Columns.Count; i++)
                                {
                                    if (xColArray[j] == pDataTable.Columns[i].ColumnName)
                                    {
                                        xFind = true;
                                        UTF8_WriteString(writer, xColCapArray[j - 1], 0, 1);//(列名)不是最后一列的处理方式
                                        x = j;
                                        break;
                                    }
                                }
                                if (xFind == false)
                                {
                                    MessageBox.Show("指定的列名不存在!");
                                    return;
                                }
                            }
                            UTF8_WriteString(writer, xColCapArray[x], 0, 2);//(列名)最后一列的处理方式
                            //--************************************************************************************************
                            //设计列数据
                            int y = 0;
                            //-------------
                            for (int b = 0; b < pDataTable.Columns.Count; b++)
                            {
                                for (int a = 0; a < xColArray.Length; a++)
                                {
                                    if (xColArray[a] == pDataTable.Columns[b].ColumnName)
                                    {
                                        y = b;//获取最大列的索引
                                    }
                                }
                            }
                            //-------------
                            for (int j = 0; j < pDataTable.Rows.Count; j++)
                            {
                                for (int i = 0; i < pDataTable.Columns.Count; i++)
                                {
                                    String pColType = pDataTable.Columns[i].DataType.Name.ToString();//获取列类型
                                    for (int k = 1; k < xColArray.Length; k++)
                                    {
                                        if (xColArray[k - 1] == pDataTable.Columns[i].ColumnName.ToString())
                                        {
                                            //***************************************************************************************
                                            //--不是最后一列的处理方式
                                            if (pDataTable.Rows[j][i].ToString() != "")
                                            {
                                                switch (pColType)
                                                {
                                                    case "String":
                                                        {
                                                            UTF8_WriteString(writer, pDataTable.Rows[j][i].ToString(), 0, 1);
                                                            break;
                                                        }
                                                    case "Int32":
                                                        {
                                                            UTF8_WriteString(writer, pDataTable.Rows[j][i].ToString(), 0, 1);
                                                            break;
                                                        }
                                                    case "Boolean":
                                                        {
                                                            UTF8_WriteBoolean(writer, Convert.ToBoolean(pDataTable.Rows[j][i]), 1, 1);
                                                            break;
                                                        }
                                                    case "DateTime":
                                                        {
                                                            UTF8_WriteDate(writer, Convert.ToDateTime(pDataTable.Rows[j][i]), "yyyy-MM-dd", 0, 1);
                                                            break;
                                                        }
                                                    case "Decimal":
                                                        {
                                                            UTF8_WriteDecimal(writer, Convert.ToDecimal(pDataTable.Rows[j][i]), 3, 0, 1);
                                                            break;
                                                        }
                                                    default:
                                                        {
                                                            UTF8_WriteString(writer, pDataTable.Rows[j][i].ToString(), 0, 1);
                                                            break;
                                                        }
                                                }
                                            }
                                            else
                                            {
                                                UTF8_WriteString(writer, "", 0, 1);
                                            }
                                        }
                                    }
                                }
                                //***********************************************************************************************
                                //********************最后一列的处理方式*********************************************************
                                String pColType1 = pDataTable.Columns[y].DataType.Name.ToString();//获取列类型
                                if (pDataTable.Rows[j][y].ToString() != "")
                                {
                                    switch (pColType1)
                                    {
                                        case "String":
                                            {
                                                UTF8_WriteString(writer, pDataTable.Rows[j][y].ToString(), 0, 2);
                                                break;
                                            }
                                        case "Int32":
                                            {
                                                UTF8_WriteString(writer, pDataTable.Rows[j][y].ToString(), 0, 2);
                                                break;
                                            }
                                        case "Boolean":
                                            {
                                                UTF8_WriteBoolean(writer, Convert.ToBoolean(pDataTable.Rows[j][y]), 1, 2);
                                                break;
                                            }
                                        case "DateTime":
                                            {
                                                UTF8_WriteDate(writer, Convert.ToDateTime(pDataTable.Rows[j][y]), "yyyy-MM-dd", 0, 2);
                                                break;
                                            }
                                        case "Decimal":
                                            {
                                                UTF8_WriteDecimal(writer, Convert.ToDecimal(pDataTable.Rows[j][y]), 3, 0, 2);
                                                break;
                                            }
                                        default:
                                            {
                                                UTF8_WriteString(writer, pDataTable.Rows[j][y].ToString(), 0, 2);
                                                break;
                                            }
                                    }
                                }
                                else
                                {
                                    UTF8_WriteString(writer, "", 0, 2);
                                }
                                //**********************************************************************************************
                            }
                        }
                        else
                        {
                            MessageBox.Show("指定的列不正确!");
                            return;
                        }
                    }
                    else
                    //--如果标题为空
                    {
                        //****************************************************************************
                        int m = 0;
                        Boolean xFind = false;
                        //****************************************************************************
                        //***********************设计列名*********************************************
                        for (int i = 1; i < xColArray.Length; i++)
                        {
                            for (int j = 0; j < pDataTable.Columns.Count; j++)
                            {
                                if (xColArray[i] == pDataTable.Columns[j].ColumnName)
                                {
                                    xFind = true;
                                    UTF8_WriteString(writer, xColArray[i - 1], 0, 1);//(列名)不是最后一列的处理方式
                                    m = i;
                                    break;
                                }
                            }
                            if (xFind == false)
                            {
                                MessageBox.Show("指定的列名不存在!");
                                return;
                            }
                        }
                        UTF8_WriteString(writer, xColArray[m], 0, 2);//(列名)最后一列的处理方式
                        //***************************************************************************
                        //设计列数据
                        int n = 0;
                        //----
                        for (int i = 0; i < pDataTable.Columns.Count; i++)
                        {
                            for (int j = 0; j < xColArray.Length; j++)
                            {
                                if (xColArray[j] == pDataTable.Columns[i].ColumnName)
                                {
                                    n = i;//获取最大列的索引值
                                }
                            }
                        }
                        //----
                        for (int i = 0; i < pDataTable.Rows.Count; i++)
                        {
                            for (int j = 0; j < pDataTable.Columns.Count; j++)
                            {
                                String pColType = pDataTable.Columns[j].DataType.Name.ToString();//获取列;类型
                                for (int k = 1; k < xColArray.Length; k++)
                                {
                                    if (xColArray[k - 1] == pDataTable.Columns[j].ColumnName.ToString())
                                    {
                                        if (pDataTable.Rows[i][j].ToString() != "")
                                        {
                                            switch (pColType)
                                            {
                                                case "String":
                                                    {
                                                        UTF8_WriteString(writer, pDataTable.Rows[i][j].ToString(), 0, 1);
                                                        break;
                                                    }
                                                case "Int32":
                                                    {
                                                        UTF8_WriteString(writer, pDataTable.Rows[i][j].ToString(), 0, 1);
                                                        break;
                                                    }
                                                case "Boolean":
                                                    {
                                                        UTF8_WriteBoolean(writer, Convert.ToBoolean(pDataTable.Rows[i][j]), 1, 1);
                                                        break;
                                                    }
                                                case "DateTime":
                                                    {
                                                        UTF8_WriteDate(writer, Convert.ToDateTime(pDataTable.Rows[i][j]), "yyyy-MM-dd", 0, 1);
                                                        break;
                                                    }
                                                case "Decimal":
                                                    {
                                                        UTF8_WriteDecimal(writer, Convert.ToDecimal(pDataTable.Rows[i][j]), 3, 0, 1);
                                                        break;
                                                    }
                                                default:
                                                    {
                                                        UTF8_WriteString(writer, pDataTable.Rows[i][j].ToString(), 0, 1);
                                                        break;
                                                    }
                                            }
                                        }
                                        else
                                        {
                                            UTF8_WriteString(writer, "", 0, 1);
                                        }
                                    }
                                }
                            }
                            //***********************************************************************************************
                            //********************最后一列的处理方式*********************************************************
                            String pColType2 = pDataTable.Columns[n].DataType.Name.ToString();//获取列类型
                            if (pDataTable.Rows[i][n].ToString() != "")
                            {
                                switch (pColType2)
                                {
                                    case "String":
                                        {
                                            UTF8_WriteString(writer, pDataTable.Rows[i][n].ToString(), 0, 2);
                                            break;
                                        }
                                    case "Int32":
                                        {
                                            UTF8_WriteString(writer, pDataTable.Rows[i][n].ToString(), 0, 2);
                                            break;
                                        }
                                    case "Boolean":
                                        {
                                            UTF8_WriteBoolean(writer, Convert.ToBoolean(pDataTable.Rows[i][n]), 1, 2);
                                            break;
                                        }
                                    case "DateTime":
                                        {
                                            UTF8_WriteDate(writer, Convert.ToDateTime(pDataTable.Rows[i][n]), "yyyy-MM-dd", 0, 2);
                                            break;
                                        }
                                    case "Decimal":
                                        {
                                            UTF8_WriteDecimal(writer, Convert.ToDecimal(pDataTable.Rows[i][n]), 3, 0, 2);
                                            break;
                                        }
                                    default:
                                        {
                                            UTF8_WriteString(writer, pDataTable.Rows[i][n].ToString(), 0, 2);
                                            break;
                                        }
                                }
                            }
                            else
                            {
                                UTF8_WriteString(writer, "", 0, 2);
                            }
                            //********************************************************************************************************
                        }
                    }
                }
            }
        }
        #endregion

        #region * 转换日期的输出格式
        /// <summary>
        /// 转换日期的输出格式
        /// </summary>
        /// <param name="pStreamWriter"></param>
        /// <param name="pValue"></param>
        /// <param name="pformat">1,2,3,4四种情况</param>
        /// <param name="pSymbol"></param>
        public static void UTF8_WriteDate(StreamWriter pStreamWriter, DateTime pValue, String pformat, int pLen, int pSymbol)
        {
            UTF8_WriteString(pStreamWriter, pValue.ToString(pformat, DateTimeFormatInfo.InvariantInfo), pLen, pSymbol);
        }
        #endregion

        #region * 转换小数的输出位数
        /// <summary>
        /// 转换小数的输出位数
        /// </summary>
        /// <param name="pStreamWriter"></param>
        /// <param name="pValue"></param>
        /// <param name="pSize">限制输出小数的位数</param>
        /// <param name="pSymbol"></param>
        public static void UTF8_WriteDecimal(StreamWriter pStreamWriter, decimal pValue, int pSize, int pLen, int pSymbol)
        {
            UTF8_WriteString(pStreamWriter, decimal.Round(pValue, pSize, MidpointRounding.AwayFromZero).ToString(), pLen, pSymbol);
        }
        #endregion

        #region * 转换Boolean值
        /// <summary>
        /// 第一种情况,输出数字0,1
        /// </summary>
        /// <param name="pStreamWriter"></param>
        /// <param name="pformat">true,false</param>
        /// <param name="pSymbol"></param>
        public static void UTF8_WriteBoolean(StreamWriter pStreamWriter, Boolean pValue, int pType, int pSymbol)
        {
            if (pType == 0)
            {
                if (pValue == true) { UTF8_WriteString(pStreamWriter, "true", 0, pSymbol); }
                if (pValue == false) { UTF8_WriteString(pStreamWriter, "false", 0, pSymbol); }
            }
            if (pType == 1)
            {
                if (pValue == true) { UTF8_WriteString(pStreamWriter, "0", 0, pSymbol); }
                if (pValue == false) { UTF8_WriteString(pStreamWriter, "1", 0, pSymbol); }
            }
        }

        /// <summary>
        /// 第二种情况,输出TRUE,FALSE
        /// </summary>
        /// <param name="pStreamWriter"></param>
        /// <param name="pValue">0,1</param>
        /// <param name="pSymbol"></param>
        public static void UTF8_WriteBoolean(StreamWriter pStreamWriter, int pValue, int pType, int pSymbol)
        {
            if (pType == 0)
            {
                if (pValue == 0) { UTF8_WriteString(pStreamWriter, "0", 0, pSymbol); }
                if (pValue == 1) { UTF8_WriteString(pStreamWriter, "1", 0, pSymbol); }
            }
            if (pType == 1)
            {
                if (pValue == 0) { UTF8_WriteString(pStreamWriter, "true", 0, pSymbol); }
                if (pValue == 1) { UTF8_WriteString(pStreamWriter, "false", 0, pSymbol); }
            }
        }
        #endregion

        #region * 写入字符串,分列符和换行符
        /// <summary>
        /// 写入字符串,分列符和换行符
        /// </summary>
        /// <param name="pStreamWriter"></param>
        /// <param name="pString"></param>
        /// <param name="pType">[1]:Add Tab   [2]:Enter</param>
        public static void UTF8_WriteString(StreamWriter pStreamWriter, string pString, int pLen, int pSymbol)
        {
            if (pLen < 0) { MessageBox.Show("你输入的长度不符合要求!"); return; }
            if (pLen == 0)
            {
                pStreamWriter.Write(pString);
            }
            else
            {
                pStreamWriter.Write(pString.Substring(0, pLen));
            }
            UTF8_WriteSymbol(pStreamWriter, pSymbol);
        }
        #endregion

        #region * 写入分列符号和回车换行符
        /// <summary>
        /// 写入分列符号和回车换行符
        /// </summary>
        /// <param name="pStreamWriter"></param>
        /// <param name="pType">[1]:Add Tab   [2]:Enter</param>
        public static void UTF8_WriteSymbol(StreamWriter pStreamWriter, int pType)
        {
            //--EFBBBF   UTF8识别标识.
            byte Symbol1 = 0X0D;
            byte Symbol2 = 0X0A;
            byte Symbol3 = 0X09;
            string vTab = ((char)Symbol3).ToString();                                  // Tab分列
            string vEnter = ((char)Symbol1).ToString() + ((char)Symbol2).ToString();   //回车换行
            if (pType == 1) { pStreamWriter.Write(vTab); }
            if (pType == 2) { pStreamWriter.Write(vEnter); }
        }
        #endregion
    }
}

导出TXT的例子:

        #region * 导出TXT文件
        private void btnExportTxt_Click(object sender, EventArgs e)
        {
            if (this.txtSaveDir.Text.Trim() != "")
            {
                if (DemoTb != null && DemoTb.Rows.Count > 0)
                {
                    ExportTxt.UTF8_SaveToTXT(DemoTb, "姓名,年龄,性别,籍贯,创建时间", "姓名,年龄,性别,籍贯,创建时间", this.txtSaveDir.Text.Trim());
                    MessageBox.Show("导出文件成功!");
                }
                else
                {
                    MessageBox.Show("数据为空,不能进行导出!");
                }
            }
            else
            {
                MessageBox.Show("导出文件目录不能为空!");
            }
        }
        #endregion

导入TXT的例子:

      #region * 导入TXT文件
        private void btnImportTxt_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.txtFindDir.Text.Trim() != "")
                {
                    byte Symbol1 = 0X0D;
                    byte Symbol2 = 0X0A;
                    string vEnter = ((char)Symbol1).ToString() + ((char)Symbol2).ToString();   //回车换行
                    //--
                    StreamReader reader = new StreamReader(this.txtFindDir.Text.Trim());
                    string str = string.Empty;
                    ArrayList arrayList = new ArrayList();
                    str = reader.ReadToEnd();
                    if (!string.IsNullOrEmpty(str))
                    {
                        string[] arrstr = str.Split(vEnter.ToCharArray());
                        foreach (string item in arrstr)
                        {
                            //去掉空行
                            if (!string.IsNullOrEmpty(item))
                            {
                                arrayList.Add(item);
                            }
                        }
                    }
                    if (arrayList != null && arrayList.Count > 0)
                    {
                        DemoTb.Clear();
                        //第二行开始,第一行为标题
                        for (int i = 1; i < arrayList.Count; i++)
                        {
                            string[] arr = arrayList[i].ToString().Split("\t".ToCharArray());
                            DataRow dr = DemoTb.NewRow();
                            dr["姓名"] = arr[0];
                            dr["年龄"] = arr[1];
                            dr["性别"] = arr[2];
                            dr["籍贯"] = arr[3];
                            dr["创建时间"] = arr[4];
                            DemoTb.Rows.Add(dr);
                        }
                    }
                    this.dataGridView1.DataSource = DemoTb;
                }
                else
                {
                    MessageBox.Show("导入文件目录不能为空!");
                }
            }
            catch (Exception eMsg)
            {
                MessageBox.Show("导入数据出错:" + eMsg.ToString());
            }
        }
        #endregion

以上即可完成对TXT文件的导入导出。

你可能感兴趣的:(txt)