【问题标题】:C# would like to convert Excel to Text FileC# 想将 Excel 转换为文本文件
【发布时间】:2017-09-12 10:41:28
【问题描述】:

这是我的 C# 代码,Visual Studio 2015。

我想保存这些 Excel 单元格以转换文本文件。

例如,从AN50中选择AN1中的值,然后保存

“Range1.txt”。

非常感谢。

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

【问题讨论】:

  • 用代码而不是代码图像格式化问题
  • 看到这个代码stackoverflow.com/questions/25332404/…你可以通过这样的代码修改你的excel文件
  • 这是您尝试解决的另一个问题 - 当您有一堆提取的文本时如何写入文本文件。只需搜索该问题并结合您已有的内容

标签: c# excel text cell


【解决方案1】:

对于这么小的范围,我想说您可以很容易地循环遍历该范围内的所有单元格并将它们转储到文件中。也就是说,如果您的文件变大或格式发生变化(例如 CSV),那么我认为您会后悔使用迭代方法的那一天。

就性能而言,Excel 导出到文本/CSV 会影响您能想到的任何 COM 实现。

即使您的示例很小,我还是建议您让 Excel 完成繁重的工作,因为无论如何您已经调用了 COM。这是一个基本示例:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 2021-12-06
    相关资源
    最近更新 更多