简体   繁体   English

循环使用Excel工作表并使用C#将文本保存到TXT文件中

[英]Loop through Excel worksheets and save text into a TXT file with C#

I have most of the problem solved. 我解决了大部分问题。 I can loop through the worksheets, I can create the text file and write to it. 我可以遍历工作表,我可以创建文本文件并写入它。 The only problem I'm having is actually extracting the text or values from every sheet. 我遇到的唯一问题实际上是从每张表中提取文本或值。 Below is the code I have, but it only throws an object per worksheet and writes those words into my text file instead of the actual values. 下面是我的代码,但它只会为每个工作表抛出一个对象,并将这些单词写入我的文本文件而不是实际值。

System.Object[,]
System.Object[,]

What else am I missing? 我还缺少什么? I should point out I'm a beginner programmer. 我应该指出我是一名初学程序员。

Here's the code I have so far: 这是我到目前为止的代码:

using (StreamWriter sw = File.CreateText("ExtractedText.txt"))
{
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook thisWkBook = xlApp.Workbooks.Open(thisFile);

    foreach (Excel.Worksheet sheet in thisWkBook.Worksheets)
    {
        sw.WriteLine(sheet.UsedRange.Value);
    }
}

Any ideas? 有任何想法吗? Thanks! 谢谢!

Something like this, not tested. 像这样的东西,没有经过测试。 See http://dontbreakthebuild.com/2011/01/30/excel-and-c-interop-with-net-4-how-to-read-data-from-excel/ 请参阅http://dontbreakthebuild.com/2011/01/30/excel-and-c-interop-with-net-4-how-to-read-data-from-excel/

using (StreamWriter sw = File.CreateText("ExtractedText.txt"))
{
    var excelApp = new Excel.Application();
    var workBook = excelApp.Workbooks.Open(thisFile);

    foreach (var sheet in workBook.Worksheets)
    {
      foreach (var row in sheet.UsedRange.Rows)
      {
        foreach (var cell in row.Columns)
        {
          sw.Write(cell.Value + " ");
        } 
        sw.WriteLine();
      }
    }
}

您需要从工作表中获取数据,例如:

sw.WriteLine(sheet.Range["C5"].Value.ToString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM