2012-06-27 7 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)을 당길 수 있어야

:

각 라인은 각 필드의 문자 수는 다음과 가질 수 있으며 각 라인에서 뽑아 5 개 개의 필드가 있습니다 10,17,10 및 Excel에서 행에 자신의 셀에 배치하십시오. 셀을 당길 수는 있지만 현재는 셀 구분을 기반으로합니다. 필드가 전체 공간을 차지하지 않아 빈 셀이있는 Excel 시트로 끝나면 문제가 발생합니다.

답변

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

관련 문제