2012-06-27 331 views
4

我正在處理將.txt文件(非分隔符)轉換爲Excel電子表格的腳本。我的問題發生在我需要提取可能在5-10個字符之間的數據的地方,並且每行有幾組數據。將.txt文件導入到.xlsx文件

每行可以有以下數中的每個字段中的字符,並有五個字段中的每一行拉:

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表單。

回答

1

您可以使用String.Substring(你的標籤讀取C#):如果導入在Excel中需要

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); 
    } 
    } 
} 
0

您可以使用Mid()來獲取字符串的特定部分。如果一行在currentLine舉行,你可以提取這樣的字段:

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

等。

1

無碼(DATA,獲取外部數據,文字,固定寬度):

SO1228000 example