首页 > Web开发 > 详细

.NET从EXCEL文件导入数据

时间:2014-06-14 09:23:53      阅读:409      评论:0      收藏:0      [点我收藏+]

.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。提示


       bubuko.com,布布扣


      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();
    }

 

结果


        bubuko.com,布布扣

       bubuko.com,布布扣

         




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文件。

.NET从EXCEL文件导入数据,布布扣,bubuko.com

.NET从EXCEL文件导入数据

原文:http://blog.csdn.net/cfl20121314/article/details/30546777

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!