从Excel读取一系列数据

时间:2012-06-19 06:01:22

标签: c# excel

我很擅长使用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 Veriosn:Microsoft.Jet.OLEDB.4.0,它运行正常。但是由于我们已经迁移到64位服务器,我们必须使用最新的OleDb 12.0引擎。每次我指定一个范围(“B4:IV65536”)并尝试读取数据时,我会得到以下异常:

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

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

请建议我解决方法。

谢谢, 阿比纳夫

0 个答案:

没有答案