C# 将.txt文件导入.xlsx文件

C# 将.txt文件导入.xlsx文件,c#,excel,import,xlsx,text-files,C#,Excel,Import,Xlsx,Text Files,我正在编写一个脚本,将.txt文件(非分隔)转换为Excel电子表格。我的问题发生在需要提取5-10个字符之间的数据,并且每行上有多组数据的地方 每行的每个字段中可以包含以下数量的字符,并且每行中有五个字段要拉入: 我基本上需要能够提取10,10,10,17,10,并将它们放在Excel中自己的单元格中。我可以按现在的方式提取单元格,但它是基于空间定界的,当字段没有占用全部空间时,就会出现问题,最后我得到一个Excel工作表,其中有空白单元格。您可以使用Mid()获取字符串的特定部分。如果在cu

我正在编写一个脚本,将.txt文件(非分隔)转换为Excel电子表格。我的问题发生在需要提取5-10个字符之间的数据,并且每行上有多组数据的地方

每行的每个字段中可以包含以下数量的字符,并且每行中有五个字段要拉入:

我基本上需要能够提取10,10,10,17,10,并将它们放在Excel中自己的单元格中。我可以按现在的方式提取单元格,但它是基于空间定界的,当字段没有占用全部空间时,就会出现问题,最后我得到一个Excel工作表,其中有空白单元格。

您可以使用Mid()获取字符串的特定部分。如果在
currentLine
中保留一行,则可以提取如下字段:

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

依此类推。

您可以使用
String.Substring
(您的标记为
C
):


如果导入来自Excel(数据、获取外部数据、来自文本、固定宽度),则不需要代码:

Dim fields(5)
fields(1) = Mid(currentLine, 1, 10)
fields(2) = Mid(currentLine, 11, 10)
fields(3) = Mid(currentLine, 21, 10)
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);
     }
  }
}