0

Here is my C# code, Visual Studio 2015.

I would like to save those Excel cells to convert Text File.

For example, selecting values from AN1 from AN50, then save

"Range1.txt".

Thanks a lot.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace WindowsFormsApplication4
{
static class Program
{
    /// <summary>
    [STAThread]
    static void Main()
    {
        string testingExcel = @"V:\000.xlsx";
        Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
        Workbook xlWorkbook = xlApp.Workbooks.Open(testingExcel, Type.Missing, true);
        _Worksheet xlWorksheet = (_Worksheet)xlWorkbook.Sheets[1];
        //Range xlRange = xlWorksheet.UsedRange;

        Range Range1 = xlWorksheet.get_Range("AN1","AN50");

        foreach (Range a in Range1.Rows.Cells)
        {
            Console.WriteLine("Address: " + a.Address + " - Value: " + a.Value);
        }

        Range Range2 = xlWorksheet.get_Range("AO1", "AO50");

        foreach (Range b in Range2.Rows.Cells)
        {
            Console.WriteLine("Address: " + b.Address + " - Value: " + b.Value);
        }

        xlWorkbook.Close();
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbook);
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);
    }
}
}
  • 1
    format question with code instead of code image – Azar Shaikh Sep 08 '17 at 06:20
  • See this code https://stackoverflow.com/questions/25332404/modify-interop-excel-for-opening-existing-file you can modify your excel file through code like this – Anirudha Gupta Sep 08 '17 at 06:22
  • 1
    This is a separate problem you're trying to solve - how to write to a text file when you have a bunch of extracted text. Just search for that question and combine with what you already have – j4nw Sep 08 '17 at 06:41

1 Answers1

2

For a range this small, I'd say you can pretty easily loop through all cells in the range and dump them to a file. That said, if your files get larger or your formats change (say to a CSV), then I think you will rue the day you went with the iterative approach.

Excel's export to text/CSV will smoke any COM implementation you can come up with, in terms of performance.

Even though your example is small, I'd recommend letting Excel do the heavy lifting, since you've envoked COM anyway. Here is a basic example:

Excelx.Range range = xlWorksheet.Range["AN1", "AN50"];
range.Copy();

Excelx.Workbook nb = xlApp.Application.Workbooks.Add();
Excelx.Worksheet ns = nb.Sheets[1];
ns.get_Range("A1").PasteSpecial(Excelx.XlPasteType.xlPasteValuesAndNumberFormats);
nb.Application.DisplayAlerts = false;
nb.SaveAs("Range.txt", Excelx.XlFileFormat.xlTextWindows);
nb.Close();
xlApp.Application.DisplayAlerts = true;
Hambone
  • 15,600
  • 8
  • 46
  • 69