C#数据转换实现EXCEL到TXT文档

C#数据转换前excel中的数据格式如下:

创新互联是一家朝气蓬勃的网站建设公司。公司专注于为企业提供信息化建设解决方案。从事网站开发,网站制作,网站设计,网站模板,微信公众号开发,软件开发,微信平台小程序开发,10多年建站对成都宣传片制作等多个方面,拥有丰富的网站运维经验。

设备名称 规格型号 设备编号  使用部门 固定资产编号

电脑1 IBM5660 10001 管理部 100010001

电脑2 IBM5661 10002 研发部 100010002

电脑3 IBM5662 10003 管理部 100010003

C#数据转换到TXT文档的格式:

"检测设备资产标签","设备名称","电脑1","规格型号","IBM5660","设备编号","10001","使用部门","管理部","固定资产编号","100010001"

"检测设备资产标签","设备名称","电脑2","规格型号","IBM5661","设备编号","10002","使用部门","研发部","固定资产编号","100010002"

"检测设备资产标签","设备名称","电脑3","规格型号","IBM5662","设备编号","10003","使用部门","管理部","固定资产编号","100010003"
end

页面设计代码:

 
 
 
  1. namespace ExcelToTxt  
  2. {  
  3.     partial class Form1  
  4.     {  
  5.         ///  
  6.         /// 必需的设计器变量。  
  7.         ///  
  8.         private System.ComponentModel.IContainer components = null;  
  9.  
  10.         ///  
  11.         /// 清理所有正在使用的资源。  
  12.         ///  
  13.         ///  name="disposing">如果应释放托管资源,为 true;否则为 false。 
  14.         protected override void Dispose(bool disposing)  
  15.         {  
  16.             if (disposing && (components != null))  
  17.             {  
  18.                 components.Dispose();  
  19.             }  
  20.             base.Dispose(disposing);  
  21.         }  
  22.  
  23.         #region Windows 窗体设计器生成的代码  
  24.  
  25.         ///  
  26.         /// 设计器支持所需的方法 - 不要  
  27.         /// 使用代码编辑器修改此方法的内容。  
  28.         ///  
  29.         private void InitializeComponent()  
  30.         {  
  31.             this.dgvShow = new System.Windows.Forms.DataGridView();  
  32.             this.btnSelect = new System.Windows.Forms.Button();  
  33.             this.btnChange = new System.Windows.Forms.Button();  
  34.             ((System.ComponentModel.ISupportInitialize)(this.dgvShow)).BeginInit();  
  35.             this.SuspendLayout();  
  36.             //   
  37.             // dgvShow  
  38.             //   
  39.             this.dgvShow.AllowUserToAddRows = false;  
  40.             this.dgvShow.AllowUserToDeleteRows = false;  
  41.             this.dgvShow.AllowUserToResizeRows = false;  
  42.             this.dgvShow.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;  
  43.             this.dgvShow.Dock = System.Windows.Forms.DockStyle.Top;  
  44.             this.dgvShow.Location = new System.Drawing.Point(0, 0);  
  45.             this.dgvShow.Name = "dgvShow";  
  46.             this.dgvShow.RowTemplate.Height = 23;  
  47.             this.dgvShow.Size = new System.Drawing.Size(885, 600);  
  48.             this.dgvShow.TabIndex = 0;  
  49.             //   
  50.             // btnSelect  
  51.             //   
  52.             this.btnSelect.Location = new System.Drawing.Point(202, 611);  
  53.             this.btnSelect.Name = "btnSelect";  
  54.             this.btnSelect.Size = new System.Drawing.Size(148, 23);  
  55.             this.btnSelect.TabIndex = 1;  
  56.             this.btnSelect.Text = "选择excel文件";  
  57.             this.btnSelect.UseVisualStyleBackColor = true;  
  58.             this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click);  
  59.             //   
  60.             // btnChange  
  61.             //   
  62.             this.btnChange.Location = new System.Drawing.Point(403, 611);  
  63.             this.btnChange.Name = "btnChange";  
  64.             this.btnChange.Size = new System.Drawing.Size(152, 23);  
  65.             this.btnChange.TabIndex = 2;  
  66.             this.btnChange.Text = "转换为txt文档";  
  67.             this.btnChange.UseVisualStyleBackColor = true;  
  68.             this.btnChange.Click += new System.EventHandler(this.btnChange_Click);  
  69.             //   
  70.             // Form1  
  71.             //   
  72.             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);  
  73.             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;  
  74.             this.ClientSize = new System.Drawing.Size(885, 646);  
  75.             this.Controls.Add(this.btnChange);  
  76.             this.Controls.Add(this.btnSelect);  
  77.             this.Controls.Add(this.dgvShow);  
  78.             this.Name = "Form1";  
  79.             this.Text = "文件转换";  
  80.             ((System.ComponentModel.ISupportInitialize)(this.dgvShow)).EndInit();  
  81.             this.ResumeLayout(false);  
  82.  
  83.         }  
  84.  
  85.         #endregion  
  86.  
  87.         private System.Windows.Forms.DataGridView dgvShow;  
  88.         private System.Windows.Forms.Button btnSelect;  
  89.         private System.Windows.Forms.Button btnChange;  
  90.     }  

C#数据转换实现代码:

 
 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Data.OleDb;  
  6. using System.Drawing;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.IO;  
  10.  
  11.  
  12. namespace ExcelToTxt  
  13. {  
  14.     public partial class Form1 : Form  
  15.     {  
  16.         private DataTable dt; //存储EXCLE中的数据  
  17.  
  18.         public Form1()  
  19.         {  
  20.             InitializeComponent();  
  21.             this.btnChange.Enabled = false;//初始化设置控件为不可用  
  22.         }  
  23.  
  24.  
  25.         ///   
  26.         /// 该方法打开一个Excel文件  
  27.         ///   
  28.         ///   
  29.         ///   
  30.         private void btnSelect_Click(object sender, EventArgs e)  
  31.         {  
  32.             string excelFilePath = ""; //存储打开的文件的路径  
  33.               
  34.             OpenFileDialog selectFile = new OpenFileDialog();  
  35.               
  36.             //选择打开的文件设置  
  37.             selectFile.Filter = "Excel(*.xls)|*.xls";  
  38.             selectFile.FilterIndex = 1;  
  39.             selectFile.DefaultExt = "xls";  
  40.             selectFile.AddExtension = true;  
  41.             selectFile.RestoreDirectory = true;  
  42.             selectFile.Multiselect = false;  
  43.               
  44.             //选择文件  
  45.             if (selectFile.ShowDialog() == DialogResult.OK)  
  46.             {  
  47.                 excelFilePath = selectFile.FileName;//获取选择的文件路径  
  48.             }  
  49.             else 
  50.             {  
  51.                 return;  
  52.             }  
  53.  
  54.             //得到控件的数据源  
  55.             dt = GetExcelData(excelFilePath);  
  56.  
  57.             //在显示控件中显示数据  
  58.             ShowDataGridView();  
  59.  
  60.             //设置转换格式的控件可用  
  61.             this.btnChange.Enabled = true;  
  62.         }  
  63.  
  64.  
  65.         ///   
  66.         ///该方法将选择的EXCEL文件转换成TXT文档   
  67.         ///   
  68.         ///   
  69.         ///   
  70.         private void btnChange_Click(object sender, EventArgs e)  
  71.         {  
  72.             string txtFilePath = "";//存储选择的TXT文档的文件名  
  73.             SaveFileDialog saveTxtFile = new SaveFileDialog();  
  74.  
  75.             //选择保存的文件设置  
  76.             saveTxtFile.Filter = "Text(.txt)|*.txt";  
  77.             saveTxtFile.FilterIndex = 1;  
  78.             saveTxtFile.DefaultExt = "txt";  
  79.             saveTxtFile.AddExtension = true;  
  80.             saveTxtFile.RestoreDirectory = true;  
  81.             saveTxtFile.OverwritePrompt = true;  
  82.  
  83.             //选择创建文件的文件夹  
  84.             if (saveTxtFile.ShowDialog() == DialogResult.OK)  
  85.             {  
  86.                 txtFilePath = saveTxtFile.FileName; //获取选择的文件路径  
  87.             }  
  88.             else 
  89.             {  
  90.                 return;  
  91.             }  
  92.  
  93.             //将DataTable中的文件写入到txt文档中  
  94.             Cursor.Current = Cursors.WaitCursor; //设置鼠标状态  
  95.             int dtcols = dt.Columns.Count;  
  96.             StringBuilder sbtxtdata = new StringBuilder(); ;  //临时存储从dt中读出的每一条数据  
  97.  
  98.  
  99.             //先创建一个新的TXT文档  
  100.             FileStream fsTxtFile = new FileStream(txtFilePath, FileMode.CreateNew, FileAccess.Write);  
  101.             StreamWriter swTxtFile = new StreamWriter(fsTxtFile, Encoding.GetEncoding("gb2312") );  
  102.  
  103.             if (dtcols > 3)  
  104.             {  
  105.                 string[] tempstr = new string[11];  
  106.                   
  107.                 //设置固定的值  
  108.                 tempstr[0] = "\"" + "检测设备资产标签" + "\"" + ",";  
  109.                 tempstr[1] = "\"" + "设备名称" + "\"" + ",";  
  110.                 tempstr[3] = "\"" + "规格型号" + "\"" + ",";  
  111.                 tempstr[5] = "\"" + "设备编号" + "\"" + ",";  
  112.                 tempstr[7] = "\"" + "使用部门" + "\"" + ",";  
  113.                 tempstr[9] = "\"" + "固定资产编号" + "\"" + ",";   
  114.                   
  115.                 //标签2的格式写入Txt文档  
  116.                 for(int rows = 0; rows < dt.Rows.Count; rows++)  
  117.                 {  
  118.                     for (int cols = 0; cols < dt.Columns.Count; cols++)  
  119.                     {  
  120.                         int tempindex = 2*(cols+1);  
  121.                         tempstr[tempindex] = "\"" + dt.Rows[rows][cols].ToString() + "\"";  
  122.                     }  
  123.  
  124.                     tempstr[2] = tempstr[2] + ",";  
  125.                     tempstr[4] = tempstr[4] + ",";  
  126.                     tempstr[6] = tempstr[6] + ",";  
  127.                     tempstr[8] = tempstr[8] + ",";  
  128.                     tempstr[10] = tempstr[10] + "\r\n";  
  129.  
  130.                     //将本行数据写入缓冲区  
  131.                     foreach (string str in tempstr)  
  132.                     {  
  133.                         sbtxtdata.Append(str);  
  134.                     }  
  135.                     swTxtFile.Write(sbtxtdata);  
  136.                       
  137.                     //清空本行中的数据  
  138.                     sbtxtdata.Remove(0, sbtxtdata.Length);  
  139.  
  140.                     //将数组中新添加的数据清空  
  141.                     for (int i = 0; i < dt.Columns.Count; i++)  
  142.                     {  
  143.                         int tempindex = 2*(i+1);  
  144.                         tempstr[tempindex] = "";  
  145.                     }  
  146.                 }  
  147.             }  
  148.             else 
  149.             {  
  150.                 string[] tempstr = new string[5];  
  151.                 //标签0或1的格式写入Txt文档  
  152.                 for (int rows = 0; rows < dt.Rows.Count; rows++)  
  153.                 {  
  154.                     for (int cols = 0; cols < dt.Columns.Count; cols++)  
  155.                     {  
  156.                         string temp = "";//临时存储当前时间  
  157.  
  158.                         if (cols == 0)  
  159.                         {  
  160.                             tempstr[0] = "\"" + dt.Rows[rows][cols] + "\"" + ",";  
  161.                         }  
  162.                         else if (cols == 1)  
  163.                         {  
  164.                             temp = dt.Rows[rows][cols].ToString();  
  165.                             tempstr[1] = "\"" + temp.Substring(0, 4) + "\"" + ","; //截取年  
  166.                             tempstr[2] = "\"" + temp.Substring(4, 2) + "\"" + ","; //截取月  
  167.                             tempstr[3] = "\"" + temp.Substring(6, 2) + "\"" + ","; //截取日  
  168.                         }  
  169.                         else if (cols == 2)  
  170.                         {  
  171.                             tempstr[4] = "\"" + dt.Rows[rows][cols] + "\"" + "\r\n";  
  172.                         }  
  173.                     }  
  174.  
  175.                     //将本行数据写入缓冲区  
  176.                     foreach (string str in tempstr)  
  177.                     {  
  178.                         sbtxtdata.Append(str);  
  179.                     }  
  180.                     swTxtFile.Write(sbtxtdata);  
  181.  
  182.                     //清空本行中的数据  
  183.                     sbtxtdata.Remove(0, sbtxtdata.Length);  
  184.  
  185.                     //将数组中新添加的数据清空  
  186.                     for (int i = 0; i < dt.Columns.Count; i++)  
  187.                     {  
  188.                         tempstr[i] = "";  
  189.                     }  
  190.                 }  
  191.             }  
  192.  
  193.             //将数据写入文档  
  194.             swTxtFile.Write("end");  
  195.             swTxtFile.Flush();  
  196.             swTxtFile.Close();  
  197.             fsTxtFile.Close();  
  198.  
  199.             //重新设置鼠标格式  
  200.             Cursor.Current = Cursors.Default;  
  201.             MessageBox.Show("文件转换成功!", "提示",  
  202.                     MessageBoxButtons.OK,  MessageBoxIcon.Information);  
  203.         }  
  204.  
  205.  
  206.         ///   
  207.         /// 获取Excel文件中的数据  
  208.         ///   
  209.         /// Excel文件的路径  
  210.         /// DataTable:将Excel文件的数据加载到DataTable中  
  211.         private DataTable GetExcelData(string path)  
  212.         {  
  213.             //连接字符串确定  
  214.             string excelstr = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source= " + path + " ;"   
  215.                         + " Extended Properties = Excel 8.0;";  
  216.               
  217.             OleDbConnection excelConn = new OleDbConnection(excelstr);  
  218.  
  219.             //打开数据源连接  
  220.             try 
  221.             {  
  222.                 if (excelConn.State == ConnectionState.Closed)  
  223.                 {  
  224.                     excelConn.Open();  
  225.                 }  
  226.             }  
  227.             catch (Exception ex)  
  228.             {  
  229.                 MessageBox.Show("打开数据源连接失败!", "错误",   
  230.                         MessageBoxButtons.OK, MessageBoxIcon.Error);  
  231.                 Application.Exit();  
  232.             }  
  233.             finally 
  234.             {  
  235.                 if(excelConn.State == ConnectionState.Open)  
  236.                 excelConn.Close();  
  237.             }  
  238.  
  239.             //设置查询命令  
  240.             OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", excelConn);  
  241.             DataSet ds = new DataSet();  
  242.               
  243.             //执行该查询EXCEL表的命令  
  244.             try 
  245.             {  
  246.                 myCommand.Fill(ds, "excelTable");  
  247.             }  
  248.             catch (Exception ex)  
  249.             {  
  250.                 MessageBox.Show("该Excel文件的工作表的名字不是[Sheet1$]!", "错误",   
  251.                                       MessageBoxButtons.OK, MessageBoxIcon.Error);  
  252.                 Application.Exit();  
  253.             }  
  254.             finally 
  255.             {  
  256.                 if (excelConn.State == ConnectionState.Closed)  
  257.                 {  
  258.                     excelConn.Close();  
  259.                 }  
  260.             }  
  261.  
  262.             //判断DataTable中是否有数据  
  263.             if (ds.Tables["excelTable"].Rows.Count > 0)  
  264.             {  
  265.                 return ds.Tables["excelTable"];  
  266.             }  
  267.             else 
  268.             {  
  269.                 MessageBox.Show("没有读到Excel表中的数据!", "错误",   
  270.                        &nb

    分享名称:C#数据转换实现EXCEL到TXT文档
    网页链接:http://www.shufengxianlan.com/qtweb/news22/154772.html

    网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

    广告

    声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联