将 .txt 文件导入到 .xlsx 文件

4
我正在处理一个将非分隔的.txt文件转换成Excel电子表格的脚本。我的问题在于需要提取可能在每行中出现的5-10个字符的数据,而每行中有几组数据。
每行中的每个字段可以具有以下数量的字符,并且每行中有5个要提取的字段:
10 char    10 char   10 char  17 char           10 char

523452    D918      20120418  1FD7X2XTACEB8963820120606  
523874    L9117244  20120409  3C6TDT5H0CG12130200000000
535581    G700      20120507  5GYFUD CT        00000000

我需要能够将10,10,10,17,10提取出来,并将它们放在Excel的一行中的各自单元格中。目前我已经能够提取单元格,但是这基于空格分隔,当字段没有占满全部空间时会导致问题,最终在Excel表格中留下空白单元格。

3个回答

1
您可以使用 String.Substring(您的标签为 C#):
using System;
using System.IO;

class Test 
{
  public static void Main() 
  {
     try 
     {
        // Create an instance of StreamReader to read from a file.
        // The using statement also closes the StreamReader.
        using (StreamReader sr = new StreamReader("TestFile.txt")) 
        {
            String line;
            // Read and display lines from the file until the end of 
            // the file is reached.
            while ((line = sr.ReadLine()) != null) 
            {
                String Chunk1 = line.Substring( 0, 10);  // First 10
                String Chunk2 = line.Substring(10, 10);  // Second 10
                String Chunk3 = line.Substring(20, 10);  // Third 10
                String Chunk4 = line.Substring(30, 17);  // Now 17
                String Chunk5 = line.Substring(47);      // Remainder (correction: Chunk2 --> Chunk5)
                Console.WriteLine("Chunks 1: {0} 2: {1} 3: {2} 4: {3} 5: {4})",
                     Chunk1, Chunk2, Chunk3, Chunk4, Chunk5);

            }
            Console.ReadLine();
        }
     }
     catch (Exception e) 
     {
        // Let the user know what went wrong.
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
     }
  }
}

1
如果从Excel内部导入(数据,获取外部数据,从文本,固定宽度),则不需要编写代码。

SO1228000 example


0

你可以使用 Mid() 函数来获取字符串的特定部分。如果一行被保存在 currentLine 中,你可以像这样提取字段:

Dim fields(5)
fields(1) = Mid(currentLine, 1, 10)
fields(2) = Mid(currentLine, 11, 10)
fields(3) = Mid(currentLine, 21, 10)

等等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接