解决OLE DB连接问题,无需安装数据连接组件

本文关键字:连接 安装 数据 组件 OLE DB 问题 解决 | 更新日期: 2023-09-27 18:19:12

是否有办法解决OLEDB连接(microsoft.ace.oledb.12.0'提供程序未在本地机器上注册)的问题,而不安装数据连接组件,同时读取excel文件

请建议。

解决OLE DB连接问题,无需安装数据连接组件

尝试下面的代码

using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using ExcelTools = Ms.Office;
using Excel = Microsoft.Office.Interop.Excel;
namespace Tests
{
    [TestFixture]
    public class ExcelSingle
    {
        [Test]
        public void ProcessWorkbook()
        {
            string file = @"C:'Users'Chris'Desktop'TestSheet.xls";
            Console.WriteLine(file);
            Excel.Application excel = null;
            Excel.Workbook wkb = null;
            try
            {
                excel = new Excel.Application();
                wkb = ExcelTools.OfficeUtil.OpenBook(excel, file);
                Excel.Worksheet sheet = wkb.Sheets["Data"] as Excel.Worksheet;
                Excel.Range range = null;
                if (sheet != null)
                    range = sheet.get_Range("A1", Missing.Value);
                string A1 = String.Empty;
                if( range != null )
                    A1 = range.Text.ToString();
                Console.WriteLine("A1 value: {0}", A1);
            }
            catch(Exception ex)
            {
                //if you need to handle stuff
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (wkb != null)
                    ExcelTools.OfficeUtil.ReleaseRCM(wkb);
                if (excel != null)
                    ExcelTools.OfficeUtil.ReleaseRCM(excel);
            }
        }
    }
}