Need a sample code that converts a file from excel to a regular txt file

  • Csv file ... or which thread to work with eksel - Vitaly Shebanits
  • 2
    How do you want to convert tables, formulas and graphics into text? - tym32167
  • There are no only values ​​from the table - Denis Boykachev

1 answer 1

This is how it can be done using OLE DB:

using System; using System.Data; using System.IO; using System.Collections.Generic; using System.Data.OleDb; using System.Text; namespace ConsoleApp1 { class Program { //находит максимальную длину элемента для всех столбцов DataTable static int[] maxlen(DataTable dt) { int[] res = new int[dt.Columns.Count]; for (int i = 0; i < dt.Columns.Count; i++) { res[i] = 0; foreach (DataRow row in dt.Rows) { string s = row[i].ToString(); if (s.Length > res[i]) res[i] = s.Length; } } return res; } //выводит таблицу в текстовый файл static void print(DataTable dt, StreamWriter wr) { int[] len = maxlen(dt); foreach (DataRow row in dt.Rows) { for (int i = 0; i < row.ItemArray.Length; i++) { string s = row[i].ToString().PadLeft(len[i]); wr.Write(s + " | "); } wr.WriteLine(); } } static void Main(string[] args) { string xlspath = "c:\\test\\test.xls"; string txtpath = "c:\\test\\test.txt"; string strConn = string.Empty; string sheetName = string.Empty; var builder = new OleDbConnectionStringBuilder("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=No;IMEX=1;'"); builder.DataSource = xlspath; strConn = builder.ConnectionString; OleDbConnection conn = new OleDbConnection(strConn); using (conn) { conn.Open(); //получаем список листов DataTable dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); FileStream fs = new FileStream(txtpath, FileMode.Create); using (fs) { StreamWriter wr = new StreamWriter(fs, Encoding.UTF8); using (wr) { foreach (DataRow row in dtSchema.Rows) { //выводим имя файла sheetName = row.Field<string>("TABLE_NAME"); wr.WriteLine("* Лист "+ sheetName); wr.WriteLine(); //получаем содержимое листа DataTable tbContainer = new DataTable(); OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}]", sheetName), conn); oda.Fill(tbContainer); //выводим таблицу print(tbContainer, wr); wr.WriteLine(); } } } } Console.Write("OK"); Console.ReadKey(); } } } 

This example does not require Excel or any other software on the target machine, but:

  1. Works only in Windows (2000+).

  2. Works only in 32-bit applications.

  3. It has problems with reading data in the case when one column contains mostly numeric values ​​+ several text values ​​(text can sometimes not be read).

The last problem can be solved by setting the following registry values ​​on the target machines:

 [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Jet\4.0\Engines\Excel] ImportMixedTypes = Text TypeGuessRows = 0 
  • And why only on 32 bit? You can also find out the version of the OS and if x64, then make a connection through ACE. True, perhaps the firewood will need to be delivered. - iluxa1810
  • @ iluxa1810 Well, yes, for this you will need to install either an office, or the Access Database Engine, and it is 64-bit. - MSDN.WhiteKnight 5:06