如何在 C# 控制台中读取 excel 文件?

how read excel file in c# console?

我如何在 C# 中打开一个 excel 文件并逐个单元格读取,但只是在控制台而不是在 windowsForm 中?


using System;

namespace nms
{
  class read_from_excel_file
  {
    static void Main(string[] args)
    {
         //open excel file 
        //print(cell[1,1])
    }
  }
}

您可以添加 Nuget 包“Microsoft.Office.Interop.Excel”来实现。

这是一个演示。

string strFileName = @"D:\test.xls";
object missing = System.Reflection.Missing.Value;
Excel.Application excel = new Excel.Application();
Excel.Workbook workBook = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing,
missing, missing, missing, true, missing, missing, missing, missing, missing);
Excel.Worksheet worksheet = (Excel.Worksheet)workBook.Sheets[1];

// print cell[1,1]
Console.WriteLine(worksheet.Cells[1, 1].Value);