1

我对C#用于读取 Excel 数据非常陌生。我正在使用 Microsoft.ACE.OLEDB.12.0 读取 Excel 工作表数据。但我的问题是工作表从单元格开始B4(而不是通常A1),因此我在读取数据时遇到了困难。以下是我的方法:

   public static DataSet GetExcelFileData(String fileNameWPath, String sheetName, String rangeName, String fieldList, String whereClause)
    {
        DataSet xlsDS = new DataSet();
        String xlsFields = String.Empty;
        String xlsWhereClause = String.Empty;
        String xlsSqlString = String.Empty;
        String xlsTempPath = @"C:\temp\";
        //Copy File to temp folder locations....
        String xlsTempName = Path.GetFileNameWithoutExtension(fileNameWPath);
        xlsTempName = xlsTempName.Replace(".", String.Empty).Replace(" ", "_").Replace("-", "_").Replace("&", String.Empty).Replace("~", String.Empty) + ".xls";
        //Check if sqlFields and Where Clause is Empty....
        if (String.IsNullOrEmpty(fieldList))
            xlsFields = "*";
        else
            xlsFields = fieldList;

        if (!String.IsNullOrEmpty(whereClause))
            xlsWhereClause = whereClause;


        //String oleDBConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source ={0};Extended Properties=\"Excel 8.0; IMEX=1\"", xlsTempPath + Path.GetFileName(xlsTempName));
        String oleDBConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=NO;IMEX=0\"", xlsTempPath + Path.GetFileName(xlsTempName));

        OleDbConnection xlsConnect = null;
        try
        {
            File.Copy(fileNameWPath, xlsTempPath + Path.GetFileName(xlsTempName), true);
            xlsConnect = new OleDbConnection(oleDBConnString);
            OpenConnection(xlsConnect);

            //Get Worksheet information 
            DataTable dbSchema = xlsConnect.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dbSchema == null || dbSchema.Rows.Count < 1)
            {
                throw new Exception(String.Format("Failed to get worksheet information for {0}", fileNameWPath));
            }

            DataRow[] sheets = dbSchema.Select(String.Format("TABLE_NAME LIKE '*{0}*'", sheetName.Replace("*", String.Empty)));

            if (sheets.Length < 1)
            {
                throw new Exception(String.Format("Could not find worksheet {0} in {1}", sheetName, fileNameWPath));
            }
            else
            {
                string realSheetName = sheets[0]["TABLE_NAME"].ToString();

                //Build Sql String
                xlsSqlString = String.Format("Select {0} FROM [{1}${2}] {3}", xlsFields, sheetName, rangeName, xlsWhereClause);
                //xlsSqlString = String.Format("Select {0} FROM [{1}${2}] {3}", xlsFields, sheetName, "", xlsWhereClause);
                OleDbCommand cmd = new OleDbCommand(xlsSqlString, xlsConnect);
                OleDbDataAdapter adapter = new OleDbDataAdapter(xlsSqlString, xlsConnect);
                adapter.SelectCommand = cmd;
                adapter.Fill(xlsDS);
                return xlsDS;

            }


        }
        catch (FormatException ex)
        {
            throw ex;
        }
        catch (Exception ex2)
        {
            if (ex2.Message.ToLower().Equals("no value given for one or more required parameters."))
            {
                throw new Exception(String.Format("Error in Reading File: {0}. \n Please Check if file contains fields you request Field List: {1}", fileNameWPath, xlsFields));
            }
            throw new Exception(String.Format("Error in Reading File: {0}\n Error Message: {1}", fileNameWPath, ex2.Message + ex2.StackTrace));
        }
        finally
        {
            CloseConnection(xlsConnect);
            File.Delete(xlsTempPath + Path.GetFileName(xlsTempName));
        }
    }

此外,我尝试使用旧版本的 Jet Engine:Microsoft.Jet.OLEDB.4.0,它工作正常。但是由于我们已经迁移到 64 位服务器,我们必须使用最新的 OleDb 12.0 引擎。每次我指定一个范围(“B4:IV65536”)并尝试读取数据时,都会出现以下异常:

“Microsoft Office Access 数据库引擎找不到对象 'Report1$B4:IV65536'。请确保该对象存在并且您正确拼写了它的名称和路径名。”

另外,请注意,我尝试了许多 HDR、IMEX 的排列组合(分别将它们设置为 Yes/No 和 0/1,但这没有帮助)。

请建议我一个解决方法。

谢谢, 阿比纳夫

4

0 回答 0