[英]C# would like to convert Excel to Text File
Here is my C# code, Visual Studio 2015. 这是我的C#代码Visual Studio 2015。
I would like to save those Excel cells to convert Text File. 我想保存那些Excel单元格以转换文本文件。
For example, selecting values from AN1 from AN50, then save 例如,从AN50中选择AN1中的值,然后保存
"Range1.txt". “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. 就是说,如果文件变大或格式更改(例如CSV),那么我认为您会厌倦采用迭代方法的那一天。
Excel's export to text/CSV will smoke any COM implementation you can come up with, in terms of performance. 从性能方面来说,Excel导出为文本/ CSV会抽出您可以想到的任何COM实现。
Even though your example is small, I'd recommend letting Excel do the heavy lifting, since you've envoked COM anyway. 即使您的示例很小,但我还是建议您让Excel来承担繁重的工作,因为无论如何您都调用COM。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.