.NET從EXCEL檔案匯入資料

來源:互聯網
上載者:User

標籤:style   class   blog   code   http   tar   

.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檔案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.