从Excel 2016到C#windows应用程序读取数据

时间:2017-04-11 10:04:08

标签: c# excel

我正在开发一个应用程序,我想通过C#windows应用程序从excel 2016中读取。我写的代码(见下面的代码)在excel文件打开时工作正常。但是当我在excel文件未打开时运行代码时,它会抛出OleDbexception“外部表不是预期的格式。”

using System.Data.OleDb;
using System;

namespace ExcelRead
{
 class Program
 {
    static void Main(string[] args)
    {
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\Practice.xlsx';Extended Properties='Excel 8.0;HDR=Yes;'");
        con.Open();
        OleDbCommand cmd = new OleDbCommand("select * from [sheet1$];", con);
        OleDbDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            Console.WriteLine(dr.GetString(0) + "\t" + dr.GetString(1) + "\t" + dr.GetString(2));
        }
        Console.ReadKey();
    }
  }
}

1 个答案:

答案 0 :(得分:0)

请使用下面的代码,因为您没有维护可以生成excel表格实例的连接,这就是您收到错误的原因。

    static void Main(string[] args)
    {
            // Create Connection to Excel Workbook
            using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\Practice.xlsx';Extended Properties='Excel 8.0;HDR=Yes;'"))
            {
                OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
                connection.Open();
                // Create DbDataReader to Data Worksheet
                using (OleDbDataReader dr = command.ExecuteReader())
                {
                    Console.WriteLine(dr.GetString(0) + "\t" + dr.GetString(1) + "\t" + dr.GetString(2));
                }
            }
        Console.ReadKey();
    }