• C# OLE方式访问Excel文件


    using System;
    using System.Data;
    using System.Data.SqlClient;
    
    
    namespace Bases
    {
    /// <summary>
    /// Summary description for ExcelClass.
    /// </summary>
    public class ExcelClass
    {
    public ExcelClass()
    {
    //
    // TODO: Add constructor logic here
    //
    }
    }
    class ExcelDB
    {
    //string SPath;
    System.Data.OleDb.OleDbConnection OleDBCn;
    System.Data.OleDb.OleDbCommand OleDBCmd;
    System.Data.OleDb.OleDbDataAdapter OleAdp;
    System.Data.DataSet Ds;
    System.Data.DataTable Dt;
    /// <summary>
    /// 构造连接对象
    /// </summary>
    /// <param name="sFileName">连接字符串</param>
    public ExcelDB(string sFileName)
    {
    try
    {
    string STemp="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+sFileName+";Extended Properties=Excel 8.0;";
    System.Console.WriteLine (STemp);
    OleDBCn=new System.Data.OleDb.OleDbConnection (STemp);
    OleDBCmd=new System.Data.OleDb.OleDbCommand ();
    OleAdp=new System.Data.OleDb.OleDbDataAdapter();
    Ds=new DataSet ();
    Dt=new System.Data.DataTable  ();
    }
    catch(Exception ex)
    {
    Eric.Common.YHJMessage.ErrorMsg(ex.Source+ex.Message );
    }
    }
    
    
    public bool insertSql(string StrSql)
    {
    try
    {
    OleDBCn.Open ();
    OleDBCmd.Connection =OleDBCn;
    OleDBCmd.CommandText =StrSql;
    OleDBCmd.ExecuteNonQuery();
    return true;
    }
    catch (System.Data.OleDb.OleDbException e)
    {
    System.Console.WriteLine(e.Message );
    return false;
    }
    }
    public DataTable GetAll(string strSheet)
    {
    OleDBCn.Open();
    OleDBCmd.Connection =OleDBCn;
    
    
    OleDBCmd.CommandText ="Select * from ["+strSheet.Trim()+"$]";
    OleAdp.SelectCommand =OleDBCmd;
    try
    {
    OleAdp.Fill (Ds);
    Dt=Ds.Tables[0];
    OleDBCn.Close ();
    return Dt;
    
    
    }
    catch (System.Exception e)
    {
    Eric.Common.YHJMessage.ErrorMsg(e.Source+e.Message );
    OleDBCn.Close ();
    return null;
    }
    }
    }
    /// <summary>
    /// class ExcelDbTwo
    /// </summary>
    class ExcelDbTwo
    {
    System.Data.OleDb.OleDbConnection OleDBCn;
    System.Data.OleDb.OleDbCommand OleDBCmd;
    System.Data.OleDb.OleDbDataAdapter OleAdp;
    System.Data.DataSet Ds;
    System.Data.DataTable Dt;
    /// <summary>
    /// public ExcelDbTwo()
    /// </summary>
    public ExcelDbTwo()
    {
    
    
    }
    /// <summary>
    /// public DataTable GetDataTable(string fileDir)
    /// </summary>
    /// <param name="fileDir"></param>
    /// <returns></returns>
    public DataTable GetDataTable(string fileDir)
    {
    try
    {
    string _dbSource = "Provider=Microsoft.Jet.OLEDB.4.0;"
    + "Data Source=" + fileDir.Trim() 
    + ";Extended Properties=Excel 8.0";
    
    
    string _sheetName = "[" + "sheet" + "$]";
    
    
    //sql语句:
    string _sql = "select * from " + _sheetName;
    OleDBCn=new System.Data.OleDb.OleDbConnection (_sql);
    OleDBCmd=new System.Data.OleDb.OleDbCommand ();
    OleAdp=new System.Data.OleDb.OleDbDataAdapter();
    Ds=new DataSet ();
    Dt=new System.Data.DataTable  ();
    
    
    OleDBCn.Open ();
    OleDBCmd.Connection =OleDBCn;
    OleDBCmd.CommandText =_sheetName;
    OleDBCmd.ExecuteNonQuery();
    
    
    try
    {
    OleAdp.Fill (Ds);
    Dt=Ds.Tables[0];
    OleDBCn.Close ();
    return Dt;
    
    
    }
    catch (System.Exception e)
    {
    Eric.Common.YHJMessage.ErrorMsg(e.Source+e.Message );
    OleDBCn.Close ();
    return null;
    }
    }
    catch{return null;}
    }
    }
    }
    
    
    
    
    
    
    一. 直接调用COM组件
    (如excel 2003)引用COM组件,添加excel的com对象Microsoft Excel 11.0 Object,然后在引用中可以看到
    Microsoft.Office.Core,Excel,VBIDE三个对象。此时在程序中需要引入:
    
    
    using System.Reflection;
    using Microsoft.Office.Core;
    using Microsoft.Office.Interop.Excel;
    
    
    基本的操作方式:
       Application excel = new ApplicationClass();
                    excel.Visible = false;
                    Workbook wb = excel.Workbooks._Open(modelFile, Missing.Value, Missing.Value, Missing.Value, Missing.Value
                        , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                        , Missing.Value, Missing.Value, Missing.Value, Missing.Value);
    
    
                    Worksheet xSheet = (Worksheet)wb.Sheets[1];
    
    
            //Sheets sts = wb.Worksheets;
            //_Worksheet st = (_Worksheet)sts.get_Item(1);
            //st.Cells[3, 5] = "111"; //直接在cell上写值
            //st.Cells[2, 5] = "hahaha";
    
    
                    Range range = xSheet.get_Range("A3", "H3");
                    object[] objLines = { a200.Date, a200.PreviousClosePrice, a200.OpenPrice, a200.High, a200.Low, a200.Close, a200.Change, a200.ChangeRate };
                    range.set_Value(Missing.Value, objLines);
    
    
                    wb.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange,
                        Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
    
    
                    //wb.Close(false, Missing.Value, Missing.Value);
    
    
    //以下步骤必须进行,否则Excel在进程里不能自动释放
                    NAR(range);
                    NAR(xSheet);
                    wb.Close(false, Missing.Value, Missing.Value);
                    NAR(wb);                     
                    excel.Quit();
                    NAR(excel);
                    System.GC.Collect();
    
    
    
    
    //以往的做法是将进程里所以的Excel进程Kill掉,不推荐!
    
    
    
    
    private void NAR(object o)
            {
                try
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(o);//强制释放一个对象
                }
                catch { }
                finally
                {
                    o = null;
                }
            }
    
    
    二. 通过OLEDB操作Excel
         OleDbConnection conn = null;
                try
                {
                  //fileName 表示要操纵的Excel的文件路径,如果excel不存在,现创建它,可以通过模版文件复制创建。
                    string strConn;
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=" + fileName + ";" +
                    "Extended Properties='Excel 8.0;HDR=no;IMEX=0'";
    
    
                    conn = new OleDbConnection(strConn);
                    conn.Open();
                    System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
                    cmd.Connection = conn;
                    //在Excel的Sheet1的A3到H3处插入数据
                    cmd.CommandText = "insert into [Sheet1$A3:H3] (F1,F2,F3,F4,F5,F6,F7,F8) values('" + a200.Date + "','"
                        + a200.PreviousClosePrice + "','" + a200.OpenPrice + "','" + a200.High + "','" + a200.Low + "','" + a200.Close + "','" +
                        a200.Change + "','" + a200.ChangeRate + "')";
                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
                catch (Exception e)
                {
                    if (conn != null)
                        conn.Close();
                    Console.WriteLine(e.ToString());
                }
    
    
    注:
    1)使用 Excel 工作簿时,默认情况下,区域中的第一行是标题行(或字段名称)。如果第一个区域不包含标题,您可以在连接字符串的扩展属性中指定 HDR=NO。
    如果您在连接字符串中指定 HDR=NO,Jet OLE DB 提供程序将自动为您命名字段(F1 表示第一个字段,F2 表示第二个字段,依此类推);
    2)IMEX=1将所有读入数据
    看作字符,其他值(02)请查阅相关帮助文档;3)如果出现“找不到可安装的isam”错误,一般是连接字符串错误。
    
    
    3、从excel文件读取数据
    string sql = "select * from [sheet1$]";
    DoOleSql(sql,"test.xls");
    
    
    4、更新excel文件中的数据
    string sql = "update [sheet1$] set FieldName1='333' where FieldName2='b3'";
    DoOleSql(sql,"test.xls");
    
    
    5、向excel文件插入数据
    string sql = "insert into [sheet1$](FieldName1,FieldName2,…) values('a',’b’,…)";
    DoOleSql(sql,"test.xls");
    
    
    6、删除excel文件中的数据:不提倡使用这种方法
    7、对于非标准结构的excel表格,可以指定excel中sheet的范围
    1)读取数据:string sql = "select * from [sheet1$A3:F20]";
    2)更新数据:string sql = "update [sheet1$A9:F15] set FieldName='333' where AnotherFieldName='b3'";
    3)插入数据:string sql = "insert into [sheet1$A9:F15](FieldName1,FieldName2,…) values('a',’b’,…)";
    4)删除数据:不提倡
    注:1)代码根据需要可以自行修改;2)如果出现“操作必须使用一个可更新的查询”错误,可能sql语句中对excel文件中的“字段”引用有错误,或对excel文件不
    具有“修改”权限;3)如果出现“不能扩充选定范围”错误,可能是对excel文件引用的“范围”有错误。
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    private String[] GetExcelSheetNames(string excelFile)
    {
      OleDbConnection objConn = null;
      System.Data.DataTable dt = null;
    
    
      try
      {
        // Connection String. Change the excel file to the file you
        // will search.
        String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
            "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
        // Create connection object by using the preceding connection string.
        objConn = new OleDbConnection(connString);
        // Open connection with the database.
        objConn.Open();
        // Get the data table containg the schema guid.
        dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
     
        if(dt == null)
        {
          return null;
        }
    
    
        String[] excelSheets = new String[dt.Rows.Count];
        int i = 0;
    
    
        // Add the sheet name to the string array.
        foreach(DataRow row in dt.Rows)
        {
          excelSheets[i] = row["TABLE_NAME"].ToString();
          i++;
        }
    
    
        // Loop through all of the sheets if you want too...
        for(int j=0; j < excelSheets.Length; j++)
        {
          // Query each excel sheet.
        }
    
    
        return excelSheets;
      }
      catch(Exception ex)
      {
        return null;
      }
      finally
      {
        // Clean up.
        if(objConn != null)
        {
          objConn.Close();
          objConn.Dispose();
        }
        if(dt != null)
        {
          dt.Dispose();
        }
      }
    }
  • 相关阅读:
    创建Android项目时出错——No resource found that matches the given name 'Theme.AppCompat.Light'
    Java、Android 开发环境搭建
    tomcat7的安装与配置、及Servlet部署
    让实体对象自行决定留存操作类型(增删改)
    聚合体
    PowerDesigner15中定义varbinary(max)列
    Pig limit用法举例
    Pig join用法举例
    Pig distinct用法举例
    Pig group用法举例
  • 原文地址:https://www.cnblogs.com/devgis/p/16524161.html
Copyright © 2020-2023  润新知