In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "how to convert EXCEL into TXT documents in C#", the content is easy to understand, clear, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "how to convert EXCEL into TXT documents in C#" this article.
The data format in excel before C# data conversion is as follows:
Equipment name, specification, model, equipment number, use department fixed asset number
Computer 1 IBM5660 10001 Management Department 100010001
Computer 2 IBM5661 10002 R & D Department 100010002
Computer 3 IBM5662 10003 Management Department 100010003
Conversion of C # data to TXT document format:
"testing equipment asset label", "equipment name", "computer 1", "specification model", "IBM5660", "equipment number", "10001", "user department", "management department", "fixed assets number", "100010001"
"testing equipment asset label", "equipment name", "computer 2", "specification model", "IBM5661", "equipment number", "10002", "user department", "R & D department", "fixed asset number", "100010002"
"testing equipment asset label", "equipment name", "computer 3", "specification model", "IBM5662", "equipment number", "10003", "user department", "management department", "fixed assets number", "100010003"
End
Page design code:
Namespace ExcelToTxt {partial class Form1 {/ required designer variables. / private System.ComponentModel.IContainer components = null; / Clean up all resources in use. / if the managed resource should be released, true; otherwise false. Protected override void Dispose (bool disposing) {if (disposing & & (components! = null)) {components.Dispose ();} base.Dispose (disposing) The code generated by the region Windows forms designer supports the required method-do not use the code editor to modify the contents of this method. / / private void InitializeComponent () {this.dgvShow = new System.Windows.Forms.DataGridView (); this.btnSelect = new System.Windows.Forms.Button (); this.btnChange = new System.Windows.Forms.Button (); ((System.ComponentModel.ISupportInitialize) (this.dgvShow)) .BeginInit (); this.SuspendLayout () / dgvShow / / this.dgvShow.AllowUserToAddRows = false; this.dgvShow.AllowUserToDeleteRows = false; this.dgvShow.AllowUserToResizeRows = false; this.dgvShow.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvShow.Dock = System.Windows.Forms.DockStyle.Top This.dgvShow.Location = new System.Drawing.Point (0,0); this.dgvShow.Name = "dgvShow"; this.dgvShow.RowTemplate.Height = 23; this.dgvShow.Size = new System.Drawing.Size (885,600); this.dgvShow.TabIndex = 0 / btnSelect / / this.btnSelect.Location = new System.Drawing.Point (202611); this.btnSelect.Name = "btnSelect"; this.btnSelect.Size = new System.Drawing.Size (148,23); this.btnSelect.TabIndex = 1; this.btnSelect.Text = "Select excel file" This.btnSelect.UseVisualStyleBackColor = true; this.btnSelect.Click + = new System.EventHandler (this.btnSelect_Click); / btnChange / / this.btnChange.Location = new System.Drawing.Point (403,611); this.btnChange.Name = "btnChange" This.btnChange.Size = new System.Drawing.Size (152,23); this.btnChange.TabIndex = 2; this.btnChange.Text = "convert to txt document"; this.btnChange.UseVisualStyleBackColor = true; this.btnChange.Click + = new System.EventHandler (this.btnChange_Click) / Form1 / / this.AutoScaleDimensions = new System.Drawing.SizeF (6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size (885,646); this.Controls.Add (this.btnChange); this.Controls.Add (this.btnSelect) This.Controls.Add (this.dgvShow); this.Name = "Form1"; this.Text = "File conversion"; ((System.ComponentModel.ISupportInitialize) (this.dgvShow)) .EndInit (); this.ResumeLayout (false);} # endregion private System.Windows.Forms.DataGridView dgvShow Private System.Windows.Forms.Button btnSelect; private System.Windows.Forms.Button btnChange;}}
C # data conversion implementation code:
Using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace ExcelToTxt {public partial class Form1: Form {private DataTable dt; / / Storage data in EXCLE public Form1 () {InitializeComponent () This.btnChange.Enabled = false;// initialization setting control is not available} / this method opens an Excel file / private void btnSelect_Click (object sender, EventArgs e) {string excelFilePath = "" / / path to store open files OpenFileDialog selectFile = new OpenFileDialog (); / / Select open file settings selectFile.Filter = "Excel (* .xls) | * .xls"; selectFile.FilterIndex = 1; selectFile.DefaultExt = "xls"; selectFile.AddExtension = true SelectFile.RestoreDirectory = true; selectFile.Multiselect = false; / / Select the file if (selectFile.ShowDialog () = = DialogResult.OK) {excelFilePath = selectFile.FileName / / get the selected file path} else {return;} / / get the data source of the control dt = GetExcelData (excelFilePath); / / display the data in the display control ShowDataGridView () / / the control that sets the conversion format is available this.btnChange.Enabled = true } / this method converts the selected EXCEL file into a TXT document / private void btnChange_Click (object sender, EventArgs e) {string txtFilePath = ""; / / stores the file name of the selected TXT document SaveFileDialog saveTxtFile = new SaveFileDialog () / / Select saved file settings saveTxtFile.Filter = "Text (.txt) | * .txt"; saveTxtFile.FilterIndex = 1; saveTxtFile.DefaultExt = "txt"; saveTxtFile.AddExtension = true; saveTxtFile.RestoreDirectory = true; saveTxtFile.OverwritePrompt = true / / Select the folder if (saveTxtFile.ShowDialog () = = DialogResult.OK) where the file is created {txtFilePath = saveTxtFile.FileName; / / get the selected file path} else {return } / / write the file in DataTable to the txt document Cursor.Current = Cursors.WaitCursor; / / set the mouse state int dtcols = dt.Columns.Count; StringBuilder sbtxtdata = new StringBuilder (); / / temporarily store each piece of data read from dt / / first create a new TXT document FileStream fsTxtFile = new FileStream (txtFilePath, FileMode.CreateNew, FileAccess.Write); StreamWriter swTxtFile = new StreamWriter (fsTxtFile, Encoding.GetEncoding ("gb2312")); if (dtcols > 3) {string [] tempstr = new string [11] / / set a fixed value tempstr [0] = "\"+" detection equipment asset label "+"\ "" + ","; tempstr [1] = "\" + "device name" + "\"+", " Tempstr [3] = "\" + "specification model" + "\"+", "; tempstr [5] ="\ "" + "device number" + "\"+", "; tempstr [7] ="\ "+" user department "+"\ "" + "," Tempstr [9] = "\" + "fixed assets number" + "\"+", "; / / tag 2 is written to Txt document for (int rows = 0; rows)
< dt.Rows.Count; rows++) { for (int cols = 0; cols < dt.Columns.Count; cols++) { int tempindex = 2*(cols+1); tempstr[tempindex] = "\"" + dt.Rows[rows][cols].ToString() + "\""; } tempstr[2] = tempstr[2] + ","; tempstr[4] = tempstr[4] + ","; tempstr[6] = tempstr[6] + ","; tempstr[8] = tempstr[8] + ","; tempstr[10] = tempstr[10] + "\r\n"; //将本行数据写入缓冲区 foreach (string str in tempstr) { sbtxtdata.Append(str); } swTxtFile.Write(sbtxtdata); //清空本行中的数据 sbtxtdata.Remove(0, sbtxtdata.Length); //将数组中新添加的数据清空 for (int i = 0; i < dt.Columns.Count; i++) { int tempindex = 2*(i+1); tempstr[tempindex] = ""; } } } else { string[] tempstr = new string[5]; //标签0或1的格式写入Txt文档 for (int rows = 0; rows < dt.Rows.Count; rows++) { for (int cols = 0; cols < dt.Columns.Count; cols++) { string temp = "";//临时存储当前时间 if (cols == 0) { tempstr[0] = "\"" + dt.Rows[rows][cols] + "\"" + ","; } else if (cols == 1) { temp = dt.Rows[rows][cols].ToString(); tempstr[1] = "\"" + temp.Substring(0, 4) + "\"" + ","; //截取年 tempstr[2] = "\"" + temp.Substring(4, 2) + "\"" + ","; //截取月 tempstr[3] = "\"" + temp.Substring(6, 2) + "\"" + ","; //截取日 } else if (cols == 2) { tempstr[4] = "\"" + dt.Rows[rows][cols] + "\"" + "\r\n"; } } //将本行数据写入缓冲区 foreach (string str in tempstr) { sbtxtdata.Append(str); } swTxtFile.Write(sbtxtdata); //清空本行中的数据 sbtxtdata.Remove(0, sbtxtdata.Length); //将数组中新添加的数据清空 for (int i = 0; i < dt.Columns.Count; i++) { tempstr[i] = ""; } } } //将数据写入文档 swTxtFile.Write("end"); swTxtFile.Flush(); swTxtFile.Close(); fsTxtFile.Close(); //重新设置鼠标格式 Cursor.Current = Cursors.Default; MessageBox.Show("文件转换成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } /// /// 获取Excel文件中的数据 /// /// Excel文件的路径 /// DataTable:将Excel文件的数据加载到DataTable中 private DataTable GetExcelData(string path) { //连接字符串确定 string excelstr = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source= " + path + " ;" + " Extended Properties = Excel 8.0;"; OleDbConnection excelConn = new OleDbConnection(excelstr); //打开数据源连接 try { if (excelConn.State == ConnectionState.Closed) { excelConn.Open(); } } catch (Exception ex) { MessageBox.Show("打开数据源连接失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } finally { if(excelConn.State == ConnectionState.Open) excelConn.Close(); } //设置查询命令 OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", excelConn); DataSet ds = new DataSet(); //执行该查询EXCEL表的命令 try { myCommand.Fill(ds, "excelTable"); } catch (Exception ex) { MessageBox.Show("该Excel文件的工作表的名字不是[Sheet1$]!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } finally { if (excelConn.State == ConnectionState.Closed) { excelConn.Close(); } } //判断DataTable中是否有数据 if (ds.Tables["excelTable"].Rows.Count >0) {return ds.Tables ["excelTable"];} else {MessageBox.Show ("data not read in Excel table!", "error", MessageBoxButtons.OK, MessageBoxIcon.Error); return null }} / the data in the excel table to be selected is now in DataGridView / private void ShowDataGridView () {/ / set the style of the display control this.dgvShow.DefaultCellStyle.BackColor = Color.Beige This.dgvShow.DefaultCellStyle.Font = new Font ("Tahoma", 12); DataGridViewCellStyle highlightCellStyle = new DataGridViewCellStyle (); highlightCellStyle.BackColor = Color.Red; DataGridViewCellStyle currencyCellStyle = new DataGridViewCellStyle (); currencyCellStyle.Format = "C"; currencyCellStyle.ForeColor = Color.Green / / set the data source of the display control dgvShow.DataSource = dt;} these are all the contents of the article "how to convert EXCEL into TXT documents in C#". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.