简体   繁体   中英

C# would like to convert Excel to Text File

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);
    }
}
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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