Interop Excel将所有值读入1行

时间:2017-05-05 09:30:34

标签: c# excel-interop

我想把Excel工作表读成一个数组,但是当我读出数组时,整行的所有值都保存在第一列中,由';'分隔。

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

这是我的代码:

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

2 个答案:

答案 0 :(得分:0)

  

您可以采用第一个空白数组并循环获取值,如下所示

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

答案 1 :(得分:0)

我同意有关CSV解析器的评论,但是如果您已经开始使用Excel,它将不会自动分隔您的分号。您需要先对列执行文本。类似的东西:

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

如果大多数/所有值都是字符串,那么您可以在c#中split

前面提到的“CSV解析器”解决方案就是:

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.

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