我正在开发一个将.txt文件(非分隔)转换为Excel电子表格的脚本。我的问题出现在需要提取5到10个字符之间的数据的地方,每行都有几组数据。
每一行中每行可以包含以下字符数,每行中有五个字段:
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表格。 / p>
答案 0 :(得分: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 :(得分:1)
答案 2 :(得分:0)
您可以使用Mid()来获取字符串的特定部分。如果在currentLine
中保留一行,则可以提取如下字段:
Dim fields(5)
fields(1) = Mid(currentLine, 1, 10)
fields(2) = Mid(currentLine, 11, 10)
fields(3) = Mid(currentLine, 21, 10)
等等。