本文介绍了OleDbConnection字符串有问题-文件夹名称包含空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对OleDbConnection字符串格式有疑问。我在访问Excel文件时使用OleDb类。

I have problem with OleDbConnection string format. I use OleDb classes on access to Excel file.

这里是将excel表加载到数据集的方法。

Here is method wich load excel table to dataset.

    public  DataSet LoadExcelFileToDataSet(string file,
        string sheetName)
    {
        string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                             "Data Source=" + file + ";" +
                             "Extended Properties=Excel 8.0;";
        var oledbConn = new OleDbConnection(connString);
        try
        {
            // Open connection
            oledbConn.Open();

            // Create OleDbCommand object and select data from worksheet Sheet1
            var cmd = new OleDbCommand("SELECT * FROM [" + sheetName + "$]", oledbConn);

            // Create new OleDbDataAdapter
            var oleda = new OleDbDataAdapter { SelectCommand = cmd };

            // Create a DataSet which will hold the data extracted from the worksheet.
            var ds = new DataSet();

            // Fill the DataSet from the data extracted from the worksheet.
            oleda.Fill(ds, "SIMCards");

            return ds;
        }
        catch(Exception ex)
        {
            throw ex;
        }
        finally
        {
            // Close connection
            oledbConn.Close();
        }

    }

此方法有效。问题是如果我尝试在WPF应用程序中将此方法与相对路径一起使用。

This method works good. Problem is if I try use this method with relative path in WPF app.

LoadExcelFileToDataSet(Config\\simcard.xls,sheetName)

完整路径为:E:\C#PROJECTS\AUSK\T-TOOL\ \T-TOOL\bin\释放\Config\simcard.xls

full path is : E:\C# PROJECTS\AUSK\T-TOOL\T-TOOL\bin\Release\Config\simcard.xls

此文件夹名称为C#项目的问题-包含空格

如果从此文件夹名称中删除空格,则效果很好。

If remove white space from this folder name, it works good.

但是如何解决呢?更改文件夹名称对我来说不是解决方案。

But how to solve it? Change folder name is not solution for me.

推荐答案

您可以尝试使用类:

var sb = new System.Data.OleDb.OleDbConnectionStringBuilder();
sb.Provider = "Microsoft.Jet.OLEDB.4.0";
sb.DataSource = @"E:\C# PROJECTS\AUSK\T-TOOL\T-TOOL\bin\Release\Config\simcard.xls";
sb.Add("Extended Properties", "Excel 8.0");
MessageBox.Show(sb.ToString());

这篇关于OleDbConnection字符串有问题-文件夹名称包含空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 05:20