2

我们组织中的一个生产应用程序使用 Excel 2003 文件来处理用户通过 Web 应用程序提交的数据。此应用程序在大多数情况下都能可靠地工作。最近,应用程序开始在调用 OleDbConnection.Open() 方法时间歇性地抛出“System.Data.OleDb.OleDbException: Unspecified error”。错误一直持续到应用程序池被回收,此时一切都再次按预期运行。Windows 应用程序事件日志中未捕获任何错误。

ASP.NET Web 应用程序托管在 Windows Server 2003 32 位计算机上的 WSS 3.0 中的 Web 部件中。该应用程序旨在防止任何并发问题。系统功能 ID 是唯一有权访问临时文件存储的帐户,并且内置机制可确保在使用唯一命名约定和上传跟踪子系统的处理期间文件不会被另一个上传覆盖。

任何见解将不胜感激。

我们使用以下代码从 Excel 2003 文件中检索数据:

public static DataTable GetWorksheetData(string filePath)
{
    OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder { DataSource = filePath };
    builder.Provider = "Microsoft.Jet.OLEDB.4.0";
    builder["Extended Properties"] = "Excel 8.0;IMEX=1;HDR=YES";

    DataTable table = new DataTable();
    try
    {
        // Creates an OleDbConnection for the excel file
        using (OleDbConnection connection = new OleDbConnection(builder.ConnectionString))
        {
            connection.Open();
            string sheetName = GetWorksheet(connection, "Template");
            if (!string.IsNullOrEmpty(sheetName))
            {
                using (OleDbCommand command = connection.CreateCommand())
                {
                    try
                    {
                        command.CommandText = string.Format("SELECT * FROM [{0}]", sheetName);

                        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
                        using (DataSet dataSet = new DataSet())
                        {
                            adapter.Fill(dataSet);
                                table = dataSet.Tables[0];
                        }
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
            else
            {
                throw new InvalidWorksheetException();
            }
        }
    }
    catch (Exception ex)
    {
        Logger.Write(LogMsgSeverity.Error, ex);
        throw;
    }
    return table;
}


private static string GetWorksheet(OleDbConnection connection, string sheetName)
{
    string validSheetName = string.Empty;
    using (DataTable tables = connection.GetSchema("Tables"))
    {
        DataRowCollection rows = tables.Rows;

        if (rows.Count > 0)
        {
            foreach (DataRow row in rows)
            {
                if (row["Table_Name"].ToString().Contains(sheetName))
                {
                    validSheetName = sheetName;
                }
            }
        }
    }
    return validSheetName;
}
4

0 回答 0