【问题标题】:Put the content of multiple .txt files into Excel 2010将多个.txt文件的内容放入Excel 2010
【发布时间】:2012-02-22 20:22:21
【问题描述】:

有什么方法可以将不同的多个 .txt 文件的内容(实际上是一个文件夹中所有 .txt 文件的内容)放入 Excel 2010?我需要一个单元格 (A1) 作为文件名,另一个单元格 (A2) 作为该 .txt 文件的全部内容。其他 .txt 文件也是如此,即 B1-B2、C1-C2 等。

提前致谢。

【问题讨论】:

标签: excel


【解决方案1】:

如果CSV 可以接受,您可以编写一个小程序来读取给定目录中的所有文本文件,并以CSV 格式写出您需要的数据:

"File Name 1","Contents of File 1" 
"File Name 2","Contents of File 2"

如果您在 Excel 中打开 CSV,数据将按照您指定的方式显示。

如果您必须有一个真正的 Excel 文件(.xls、.xlsx),您可以使用 Interop 从 C# 访问 Excel 库,但这种解决方案有点复杂。

http://msdn.microsoft.com/en-us/library/ms173186(v=vs.80).aspx

您可以使用Directory.EnumerateFiles 列出所需文件夹中的所有文件名,并使用File.ReadAllText 读取每个文件的内容。

使用 CSV 文件时,正确引用输出存在一些细微差别(请参阅我的答案开头的 Wikipedia 链接)。我写了一点extension method 以便更容易输出正确引用的CSV:

   static public class Extensions
    {
        static public string CsvQuote(this string text)
        {
            if (text == null)
            {
                return string.Empty;
            }

            bool containsQuote = false;
            bool containsComma = false;
            int len = text.Length;
            for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
            {
                char ch = text[i];
                if (ch == '"')
                {
                    containsQuote = true;
                }
                else if (ch == ',')
                {
                    containsComma = true;
                }
            }

            bool mustQuote = containsComma || containsQuote;

            if (containsQuote)
            {
                text = text.Replace("\"", "\"\"");
            }

            if (mustQuote)
            {
                return "\"" + text + "\"";  // Quote the cell and replace embedded quotes with double-quote
            }
            else
            {
                return text;
            }
        }

    }

编辑:

在我的脑海中(没有经过调试或其他任何东西),写出 CSV 的代码可能如下所示:

string myDirectory = @"C:\Temp";
StringBuilder csv = new StringBuilder();
foreach (string fileName in Directory.EnumerateFiles(myDirectory))
{
    string fileContents = File.ReadAllText(fileName);
    csv.Append(fileName).Append(",").AppendLine(fileContents.CsvQuote());
}
File.WriteAllText(@"C:\SomePath\SomeFile.csv", csv.ToString());

【讨论】:

  • 是的,.csv 被接受,所以我可能会这样做,即将所有文件名及其内容放入 .csv 文件。无论如何,你能详细解释一下我怎么能做到这一点吗? :) 我是新手,所以一个简单的解释就完美了。提前致谢。
  • 更新了用于迭代文件的示例代码。您需要根据需要进行调试和修改。
猜你喜欢
  • 2012-03-15
  • 2022-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多