SoFunction
Updated on 2025-03-07

C# implements the conversion of EXCEL data to TXT documents

  using System;  
  using ;  
  using ;  
  using ;  
  using ;  
  using ;  
  using ;  
  using ;  
  using ;  

   
  namespace ExcelToTxt  
  {  
      public partial class Form1 : Form  
      {  
private DataTable dt; //Storage data in EXCLE

          public Form1()  
          {  
              InitializeComponent();  
= false;//Initialize the control to unavailable
          }  

   
          /// <summary>  
/// This method opens an Excel file
          /// </summary>  
          /// <param name="sender"></param>  
          /// <param name="e"></param>  
          private void btnSelect_Click(object sender, EventArgs e)  
          {  
string excelFilePath= "";//Storage the path of the opened file

              OpenFileDialog selectFile = new OpenFileDialog();  

//Select open file settings
               = "Excel(*.xls)|*.xls";  
               = 1;  
               = "xls";  
               = true;  
               = true;  
               = false;  

//Select file
              if (() == )  
              {  
excelFilePath=;//Get selected file path
              }  
              else 
              {  
                  return;  
              }  

//Get the control's data source
              dt = GetExcelData(excelFilePath);  

//Display data in the display control
              ShowDataGridView();  

//Controls that set conversion format are available
               = true;  
          }  

   
          /// <summary>  
///This method converts the selected EXCEL file into a TXT document
          /// </summary>  
          /// <param name="sender"></param>  
          /// <param name="e"></param>  
          private void btnChange_Click(object sender, EventArgs e)  
          {  
string txtFilePath = """;//Storing the file name of the selected TXT document
              SaveFileDialog saveTxtFile = new SaveFileDialog();  

//Select save file settings
               = "Text(.txt)|*.txt";  
               = 1;  
               = "txt";  
               = true;  
               = true;  
               = true;  

//Select the folder where the file is created
              if (() == )  
              {  
txtFilePath=;//Get selected file path
              }  
              else 
              {  
                  return;  
              }  

//Write files in DataTable into txt document
=;//Set the mouse status
              int dtcols = ;  
StringBuilder sbtxtdata = new StringBuilder(); ;  //Temporarily store every piece of data read from dt

   
// Create a new TXT document first
              FileStream fsTxtFile = new FileStream(txtFilePath, , );  
              StreamWriter swTxtFile = new StreamWriter(fsTxtFile, ("gb2312") );  

              if (dtcols > 3)  
              {  
                  string[] tempstr = new string[11];  

//Set fixed value
tempstr[0] = "\"" + "Detection equipment asset tag" +"\"" +",";
tempstr[1] = "\"" + "Device name" +"\"" +",";
tempstr[3] = "\"" + "Specification Model" + "\"" + ",";
tempstr[5] = "\"" + "Device number" + "\"" + ",";
tempstr[7] = "\"" + "User department" +"\"" + ",";
tempstr[9] = "\"" + "Fixed Asset Number" + "\"" + ",";

//Write the format of tag 2 to the Txt document
                  for(int rows = 0; rows < ; rows++)  
                  {  
                      for (int cols = 0; cols < ; cols++)  
                      {  
                          int tempindex = 2*(cols+1);  
                          tempstr[tempindex] = "\"" + [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";  

//Write the bank's data into the buffer
                      foreach (string str in tempstr)  
                      {  
                          (str);  
                      }  
                      (sbtxtdata);  

//Clear the data in this bank
                      (0, );  

//Clear the newly added data in the array
                      for (int i = 0; i < ; i++)  
                      {  
                          int tempindex = 2*(i+1);  
                          tempstr[tempindex] = "";  
                      }  
                  }  
              }  
              else 
              {  
                  string[] tempstr = new string[5];  
//Write to the Txt document in the format of tag 0 or 1
                  for (int rows = 0; rows < ; rows++)  
                  {  
                      for (int cols = 0; cols < ; cols++)  
                      {  
string temp= ";//Temporarily store the current time

                          if (cols == 0)  
                          {  
                              tempstr[0] = "\"" + [rows][cols] + "\"" + ",";  
                          }  
                          else if (cols == 1)  
                          {  
                              temp = [rows][cols].ToString();  
tempstr[1] = "\"" + (0, 4) +"\"" + " + " + "; //Intercept year
tempstr[2] = "\"" + (4, 2) +"\"" + "; //Intercept the month
tempstr[3] = "\"" + (6, 2) +"\"" + "; //Intercepted date
                          }  
                          else if (cols == 2)  
                          {  
                              tempstr[4] = "\"" + [rows][cols] + "\"" + "\r\n";  
                          }  
                      }  

//Write the bank's data into the buffer
                      foreach (string str in tempstr)  
                      {  
                          (str);  
                      }  
                      (sbtxtdata);  

//Clear the data in this bank
                      (0, );  

//Clear the newly added data in the array
                      for (int i = 0; i < ; i++)  
                      {  
                          tempstr[i] = "";  
                      }  
                  }  
              }  

//Write data to document
              ("end");  
              ();  
              ();  
              ();  

//Reset the mouse format
               = ;  
("File conversion succeeded!", "Tip",
                      ,  );  
          }  

   
          /// <summary>  
Get data in Excel file
          /// </summary>  
//// <param name="path">Path of Excel file</param>
//// <returns>DataTable: Load the data of the Excel file into the DataTable</returns>
          private DataTable GetExcelData(string path)  
          {  
//Connection string confirmation
              string excelstr = "Provider = .4.0;" + "Data Source= " + path + " ;"   
                          + " Extended Properties = Excel 8.0;";  

              OleDbConnection excelConn = new OleDbConnection(excelstr);  

//Open the data source connection
              try 
              {  
                  if ( == )  
                  {  
                      ();  
                  }  
              }  
              catch (Exception ex)  
              {  
("Opening the data source connection failed!", "Error",
                          , );  
                  ();  
              }  
              finally 
              {  
                  if( == )  
                  ();  
              }  

//Set query command
              OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", excelConn);  
              DataSet ds = new DataSet();  

//Execute the command to query the EXCEL table
              try 
              {  
                  (ds, "excelTable");  
              }  
              catch (Exception ex)  
              {  
("The sheet name of the Excel file is not [Sheet1$]!", "Error",
                                        , );  
                  ();  
              }  
              finally 
              {  
                  if ( == )  
                  {  
                      ();  
                  }  
              }  

//Judge whether there is data in the DataTable
              if (["excelTable"]. > 0)  
              {  
                  return ["excelTable"];  
              }  
              else 
              {  
("No data in Excel table was read!", "Error",
                                          , );  
                  return null;  
              }  
          }  

   
          /// <summary>  
/// Now the data in the selected excel table is in DataGridView
          /// </summary>  
          private void ShowDataGridView()  
          {  
//Set the style of the display control
               = ;  
               = new Font("Tahoma", 12);  

              DataGridViewCellStyle highlightCellStyle = new DataGridViewCellStyle();  
               = ;  

              DataGridViewCellStyle currencyCellStyle = new DataGridViewCellStyle();  
               = "C";  
               = ;  

//Set the data source of the display control
               = dt;  
          }  

      }  
  }