1

这里我使用 ADO.Net 使用指定的 connectionString 连接到 Excel 文件,它工作正常,我唯一担心的是工作表名称是否有空格字符而不是它不从相应的工作表返回列名。我的代码:

        if (extension == ".xls")
        {
            connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
            "Data Source=" + Server.MapPath("~\\ExcelUpload\\Excelsheets\\temp.xls") + ";" +
            @"Extended Properties=" + "\"Excel 8.0;HDR=YES;\"";
        }
        else if (extension == ".xlsx")
        {
            connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
            "Data Source=" + Server.MapPath("~\\ExcelUpload\\Excelsheets\\temp.xlsx") + ";" +
            @"Extended Properties=" + "\"Excel 12.0;HDR=YES;\"";
        }


        DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
        DbConnection connection = factory.CreateConnection();
        connection.ConnectionString = connectionString;
        connection.Open();

        DataTable dt;
        String[] restrection = { null, null, sheetName + "$", null };
        dt = connection.GetSchema("Columns", restrection);

那么我们如何才能将具有空格字符的 excelsheet 名称命名为 paas 呢?

4

5 回答 5

1

尝试

String[] restrictions = { null, null, "['" + sheetName + "$']", null };

因此,如果您有一个工作表 TEST WORKSHEET 它变成了“TEST WORKSHEET$”

为什么我们必须遵循这种 WIERD 命名约定,这让我无法理解

于 2013-04-18T05:47:05.200 回答
1

也许你可以使用这样的东西:

var dataset = new DataSet();
var connectionString = "connstring";
var connection = new OleDbConnection(connectionString);

connection.Open();

var sheets = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
if (sheets == null || sheets.Rows.Count < 1) throw new InvalidOperationException("CantReadWorksheets");

foreach (DataRow sheet in sheets.Rows)
{
    var tableName = sheet["Table_Name"].ToString();
    var sql = "SELECT * FROM [" + tableName + "]";

    var adap = new OleDbDataAdapter(sql, connection);
    adap.Fill(dataset, tableName);
}

connection.Close();

您可以看到我是如何获取工作表名称的。(try..catch块被剪断)

于 2013-03-13T11:06:19.370 回答
0

包含空格的文件名应该没有问题。在读取文件之前尝试检查文件是否存在:

System.IO.File.Exists(Server.MapPath("~\\ExcelUpload\\Excelsheets\\temp filename.xlsx"))
于 2013-03-13T11:03:07.550 回答
0

编码...

String[] restrection = { null, null, sheetName + "$", null };

...在工作表名称上附加一个“$”。也许工作表名称需要分隔,也许......

String[] restrection = { null, null, "[" + sheetName + "]$", null };

...或者...

String[] restrection = { null, null, "\"" + sheetName + "\"$", null };

...?

于 2013-03-13T11:15:10.647 回答
0

尝试替换这个:

connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
            "Data Source=" + Server.MapPath("~\\ExcelUpload\\Excelsheets\\temp.xls") + ";" +
            @"Extended Properties=" + "\"Excel 8.0;HDR=YES;\"";

有了这个:

string conn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path +
                              ";Extended Properties=\'Excel 8.0; HDR=YES; IMEX=1;\'";

Excel 12.0 也一样。就我而言,解决这个问题:)

于 2019-02-28T09:38:09.963 回答