.Net之路(十四)com组件、OLEDB导入EXCEL

.NET com组件


       这种方法在计算机没有安装office套件时,也是能够使用的。所以不依赖于软件,

但是还是需要xcel.exe编译后的dll文件打包到相应的程序中来引用。这样将dll文件“

随身携带”,就可以了。还是挺不错的!

 

      1.注册Microsoft.Office.Interop.Excel.dll

      

    在office安装文件夹下找到excel.exe,路径D:\Program Files(x86)\Microsoft 

Office\Office15.excel.exe文件复制到D:\ProgramFiles (x86)\Microsoft Visual

 Studio 11.0\VC下。用visual studio 2012命令行工具切换到D:\Program Files 

(x86)\Microsoft Visual Studio11.0\VC,一般会自动切换。这时候执行TlbImp /

out:Interop.Excel.dll Excel.exe。提示


       


      2.引用interop.excel.dll

      

      将编译好的dll文件复制到程序的bin文件下。添加引用


      下面是我自己做的一个小demo

          

<pre name="code" class="csharp">private void OpenExcel(string strFileName)
    {
        object missing = System.Reflection.Missing.Value;
        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//lauch excel application
        if (excel == null)
        {
            
        }
        else
        {
            excel.Visible = false;  excel.UserControl = true;
            // 以只读的形式打开EXCEL文件
            Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing,
             missing, missing, missing, true, missing, missing, missing, missing, missing);
            //取得第一个工作薄
            Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);

            //取得总记录行数   (包括标题列)
            int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行数
            //int columnsint = mySheet.UsedRange.Cells.Columns.Count;//得到列数

            //取得数据范围区域  (不包括标题列)
            Range rng1 = ws.Cells.get_Range("B2", "B" + rowsint);   //item

            Range rng2 = ws.Cells.get_Range("K2", "K" + rowsint);  //Customer
            object[,] arryItem= (object[,])rng1.Value2;   //get range's value
            object[,] arryCus = (object[,])rng2.Value2; 
            //将新值赋给一个数组
            string[,] arry = new string[rowsint-1, 2];
            for (int i = 1; i <= rowsint-1; i++)
            {
                //Item_Code列
                arry[i - 1, 0] =arryItem[i, 1].ToString();
                //Customer_Name列
                arry[i - 1, 1] = arryCus[i, 1].ToString();
            }
            //Response.Write(arry[0, 0] + "  /  " + arry[0, 1] + "#" + arry[rowsint - 2, 0] + "  /  " + arry[rowsint - 2, 1]);
        }
        excel.Quit();  excel = null;
        Process[] procs = Process.GetProcessesByName("excel");

        foreach (Process pro in procs)
        {
            pro.Kill();//没有更好的方法,只有杀掉进程
        }
        GC.Collect();
    }

 

结果


       

      

         

 
     
 
     
 
     

OLEDB方式

    这种方式就像平时使用sqlserver一样,将excel文件当成一个数据源来对待。只不过

这时候的数据库是excel罢了,其实一样简单来看sqlserver也就是复杂化的excel所以这

种方式相对还是

比较常见的。

    code

     

<pre name="code" class="csharp">/// <summary>
        /// 读取Excel数据到DS
        /// </summary>
        /// <param name="excelName">xls文件路径(服务器物理路径)string RootDir =Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录</param>
        /// <returns></returns>
        public DataSet ExcelReader(string excelName)
        {
            // 拼写连接字符串,打开连接
            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "data source=" + excelName + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
            OleDbConnection objConn = new OleDbConnection(strConn);
            objConn.Open();
            // 取得Excel工作簿中所有工作表
            DataTable schemaTable = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            OleDbDataAdapter sqlada = new OleDbDataAdapter();
            DataSet ds = new DataSet();

            // 遍历工作表取得数据并存入Dataset
            foreach (DataRow dr in schemaTable.Rows)
            {
                string strSql = "Select * From [" + dr[2].ToString().Trim() + "]";
                OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
                sqlada.SelectCommand = objCmd;
                sqlada.Fill(ds, dr[2].ToString().Trim());
            }


            objConn.Close();
            return ds;
        }

    

 
     
 
     

   几个关键code句:

    c#的垃圾回收:

  

   //得到excel所有的进程

     Process[] procs = Process.GetProcessesByName("excel");
     foreach (Process pro in procs)
     {
         pro.Kill();//
      }
     GC.Collect();


    com组件创建excel操作对象

   

  Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); //以只读的形式打开EXCEL文件
                Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);
//取得第一个工作薄
Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);
//取得单元格的值
String cellstr = ws.Cells[i][j].Value;


   oledb建立excel连接

  

// 拼写连接字符串,打开连接
            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "data source=" + excelName + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
            OleDbConnection objConn = new OleDbConnection(strConn);
objConn.Open();
// 取得Excel工作簿中所有工作表
DataTable schemaTable = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);


   

     第一种方法是创建excel对象,第二种方法是以excel为数据源。第一种的适用面更

广。还有一种是用二进制数据流的方式来读取,需要将excel文件转成csv文件。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 26
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值