首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将.txt文件导入.xlsx文件

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

Stack Overflow用户
提问于 2012-06-27 14:02:01
回答 3查看 2.6K关注 0票数 4

我正在编写一个脚本,该脚本将.txt文件(非分隔)转换为Excel电子表格。当我需要提取5-10个字符之间的数据,并且每行有几组数据时,我的问题就出现了。

每行可以在每个字段中有以下字符数,每一行有五个字段:

10焦10焦17焦10焦523452 D918 20120418 1FD7X2XTACEB 8963820120606 523874 L9117244 20120409 3C6TDT5H0CG120200000000 535581 G700 20120507 5 5GYFUD 00000000

我基本上需要能够拉出10,10,10,17,10,并将它们放在Excel中的一行单元格中。我能够像现在这样拉出单元格,但它是基于空间划界的,这会导致一个问题,当字段没有占用全部空间时,我最终得到了一个包含空白单元格的Excel表。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-06-27 15:03:06

您可以使用String.Substring (标记读取C#):

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2015-08-09 09:54:36

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

票数 1
EN

Stack Overflow用户

发布于 2012-06-27 14:23:38

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

代码语言:javascript
复制
Dim fields(5)
fields(1) = Mid(currentLine, 1, 10)
fields(2) = Mid(currentLine, 11, 10)
fields(3) = Mid(currentLine, 21, 10)

诸若此类。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11228000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档