Interop Excel 将所有值读入 1 行

Interop Excel reads all Values into 1 Line

我想将 Excel-Sheet 读入一个数组,但是当我读出数组时,整行的所有值都保存在第一列中,用 ' ;'.

如何将它们正确保存在二维数组中?

这是我的代码:

using Microsoft.Office.Interop.Excel;
using System;
using System.IO;

namespace BB_Entwurf_2
{
class Program
{
    public static void Main(string[] args)
    {
        ApplicationClass app = new ApplicationClass();
        Workbook book = null;
        Worksheet sheet = null;

        string currentDir = Environment.CurrentDirectory;
        string excelPath;
        excelPath = Path.Combine(currentDir, "MyFile.csv");

        app.Visible = false;
        app.ScreenUpdating = false;
        app.DisplayAlerts = false;

        book = app.Workbooks.Open(excelPath);

        sheet = (Worksheet)book.Worksheets[1];

        int rowCount = sheet.UsedRange.Rows.Count;

        Console.WriteLine(rowCount);

        Range range = sheet.UsedRange;

        object[,] myExcelFileValues = (object[,])range.Value2;

        range = null;

        string test = (Convert.ToString(myExcelFileValues[1,1]));

        Console.WriteLine(test);

        test = (Convert.ToString(myExcelFileValues[2,2]));

        Console.WriteLine(test);

        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(sheet);
        sheet = null;
        book.Close(false);
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(book);
        book = null;
        app.Quit();
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
        app = null;

        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}
}

You can take first blank array and take a loop to get value one by one as follow

 string[]  arr = new string[];
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(path);
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range range = worksheet.UsedRange;                  
  for (int row = 1; row <= range.Rows.Count; row++)
 {
    arr[row-1] = ((Excel.Range)range.Cells[row, 1]).Text;  
 }

我同意有关 CSV 解析器的评论,但如果您执意要使用 Excel,它不会自动分隔您的分号。您需要先执行文本到列。类似于:

range.TextToColumns(range[1, 1], XlTextParsingType.xlDelimited, XlTextQualifier.xlTextQualifierDoubleQuote, Semicolon: true);

如果 most/all 个值是字符串,您只需 split 在您的 c# 中即可。

前面提到的 "CSV parser" 解决方案就是:

excelPath = Path.Combine(currentDir, "MyFile.csv");
string[] lines = File.ReadAllLines(excelPath);
List<string[]> values = new List<string[]>();
foreach (string line in lines)
{
    values.Add(line.Split(';'));
}
// parse strings into int, double, date, etc.

实际上代码更少,无需安装...