C#讀取EXCEL檔案的三種經典方法

來源:互聯網
上載者:User

標籤:

1.方法一:採用OleDB讀取EXCEL檔案: 
把EXCEL檔案當做一個資料來源來進行資料的讀取操作,執行個體如下:
  1. public DataSet ExcelToDS(string Path) 
  2. string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;"; 
  3. OleDbConnection conn = new OleDbConnection(strConn); 
  4. conn.Open();   
  5. string strExcel = "";    
  6. OleDbDataAdapter myCommand = null; 
  7. DataSet ds = null; 
  8. strExcel="select * from [sheet1$]"; 
  9. myCommand = new OleDbDataAdapter(strExcel, strConn); 
  10. ds = new DataSet(); 
  11. myCommand.Fill(ds,"table1");    
  12. return ds; 
  13. }
複製代碼對於EXCEL中的表即sheet([sheet1$])如果不是固定的可以使用下面的方法得到
  1. string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;"; 
  2. OleDbConnection conn = new OleDbConnection(strConn); 
  3. DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,null); 
  4. string tableName=schemaTable.Rows[0][2].ToString().Trim();   
複製代碼另外:也可進行寫入EXCEL檔案,執行個體如下:
  1. public void DSToExcel(string Path,DataSet oldds) 
  2. //先得到匯總EXCEL的DataSet 主要目的是獲得EXCEL在DataSet中的結構 
  3. string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source ="+path1+";Extended Properties=Excel 8.0" ; 
  4. OleDbConnection myConn = new OleDbConnection(strCon) ; 
  5. string strCom="select * from [Sheet1$]"; 
  6. myConn.Open ( ) ; 
  7. OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom, myConn ) ; 
  8. ystem.Data.OleDb.OleDbCommandBuilder builder=new OleDbCommandBuilder(myCommand); 
  9. //QuotePrefix和QuoteSuffix主要是對builder產生InsertComment命令時使用。 
  10. builder.QuotePrefix="[";     //擷取insert語句中保留字元(起始位置) 
  11. builder.QuoteSuffix="]"; //擷取insert語句中保留字元(結束位置) 
  12. DataSet newds=new DataSet(); 
  13. myCommand.Fill(newds ,"Table1") ; 
  14. for(int i=0;i<oldds.Tables[0].Rows.Count;i++) 
  15. //在這裡不能使用ImportRow方法將一行匯入到news中,因為ImportRow將保留原來DataRow的所有設定(DataRowState狀態不變)。
  16.    在使用ImportRow後newds內有值,但不能更新到Excel中因為所有匯入行的DataRowState!=Added 
  17. DataRow nrow=aDataSet.Tables["Table1"].NewRow(); 
  18. for(int j=0;j<newds.Tables[0].Columns.Count;j++) 
  19.    nrow[j]=oldds.Tables[0].Rows[i][j]; 
  20. newds.Tables["Table1"].Rows.Add(nrow); 
  21. myCommand.Update(newds,"Table1"); 
  22. myConn.Close();
複製代碼2.方法二:引用的com組件:Microsoft.Office.Interop.Excel.dll   讀取EXCEL檔案 
首先是Excel.dll的擷取,將Office安裝目錄下的Excel.exe檔案Copy到DotNet的bin目錄下,cmd到該目錄下,運行 TlbImp EXCEL.EXE Excel.dll 得到Dll檔案。 再在項目中添加引用該dll檔案.
  1. //讀取EXCEL的方法   (用範圍地區讀取資料)
  2. private void OpenExcel(string strFileName)
  3. {
  4.     object missing = System.Reflection.Missing.Value;
  5.     Application excel = new Application();//lauch excel application
  6.     if (excel == null)
  7.     {
  8.         Response.Write("<script>alert(‘Can‘t access excel‘)</script>");
  9.     }
  10.     else
  11.     {
  12.         excel.Visible = false; excel.UserControl = true;
  13.         // 以唯讀形式開啟EXCEL檔案
  14.         Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing,
  15.          missing, missing, missing, true, missing, missing, missing, missing, missing);
  16.         //取得第一個工作薄
  17.         Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);
  18.         //取得總記錄行數   (包括標題列)
  19.         int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行數
  20.         //int columnsint = mySheet.UsedRange.Cells.Columns.Count;//得到列數
  21.         //取得資料範圍地區 (不包括標題列) 
  22.         Range rng1 = ws.Cells.get_Range("B2", "B" + rowsint);   //item
  23.         Range rng2 = ws.Cells.get_Range("K2", "K" + rowsint); //Customer
  24.         object[,] arryItem= (object[,])rng1.Value2;   //get range‘s value
  25.         object[,] arryCus = (object[,])rng2.Value2;   
  26.         //將新值賦給一個數組
  27.         string[,] arry = new string[rowsint-1, 2];
  28.         for (int i = 1; i <= rowsint-1; i++)
  29.         {
  30.             //Item_Code列
  31.             arry[i - 1, 0] =arryItem[i, 1].ToString();
  32.             //Customer_Name列
  33.             arry[i - 1, 1] = arryCus[i, 1].ToString();
  34.         }
  35.         Response.Write(arry[0, 0] + " / " + arry[0, 1] + "#" + arry[rowsint - 2, 0] + " / " + arry[rowsint - 2, 1]);
  36.     }
  37.      excel.Quit(); excel = null;
  38.     Process[] procs = Process.GetProcessesByName("excel");
  39.     foreach (Process pro in procs)
  40.     {
  41.         pro.Kill();//沒有更好的方法,只有殺掉進程
  42.     }
  43.     GC.Collect();
  44. }
複製代碼3.方法三:將EXCEL檔案轉化成CSV(逗號分隔)的檔案,用檔案流讀取(等價就是讀取一個txt文字檔)
  1. 先引用命名空間:using System.Text;和using System.IO;
  2. FileStream fs = new FileStream("d:\\Customer.csv", FileMode.Open, FileAccess.Read, FileShare.None);
  3. StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding(936));
  4. string str = "";
  5. string s = Console.ReadLine();
  6. while (str != null)
  7. {    str = sr.ReadLine();
  8.      string[] xu = new String[2];
  9.      xu = str.Split(‘,‘);
  10.      string ser = xu[0]; 
  11.      string dse = xu[1];                if (ser == s)
  12.      { Console.WriteLine(dse);break;
  13.      }
  14. }   sr.Close();
複製代碼另外也可以將資料庫資料匯入到一個txt檔案,執行個體如下:
  1. //txt檔案名稱
  2. string fn = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + "PO014" + ".txt";
  3. OleDbConnection con = new OleDbConnection(conStr); 
  4. con.Open();
  5. string sql = "select ITEM,REQD_DATE,QTY,PUR_FLG,PO_NUM from TSD_PO014";        
  6. //OleDbCommand mycom = new OleDbCommand("select * from TSD_PO014", mycon);
  7. //OleDbDataReader myreader = mycom.ExecuteReader(); //也可以用Reader讀取資料
  8. DataSet ds = new DataSet();
  9. OleDbDataAdapter oda = new OleDbDataAdapter(sql, con);
  10. oda.Fill(ds, "PO014");
  11. DataTable dt = ds.Tables[0];
  12. FileStream fs = new FileStream(Server.MapPath("download/" + fn), FileMode.Create, FileAccess.ReadWrite);
  13. StreamWriter strmWriter = new StreamWriter(fs);    //存入到文字檔中 
  14. //把標題寫入.txt檔案中 
  15. //for (int i = 0; i <dt.Columns.Count;i++)
  16. //{
  17. //    strmWriter.Write(dt.Columns[i].ColumnName + " ");
  18. //}
  19.   
  20. foreach (DataRow dr in dt.Rows)
  21. {
  22.      string str0, str1, str2, str3;
  23.      string str = "|"; //資料用"|"分隔開
  24.      str0 = dr[0].ToString();
  25.      str1 = dr[1].ToString();
  26.      str2 = dr[2].ToString();
  27.      str3 = dr[3].ToString();
  28.      str4 = dr[4].ToString().Trim();
  29.      strmWriter.Write(str0);
  30.      strmWriter.Write(str);
  31.      strmWriter.Write(str1);
  32.      strmWriter.Write(str);
  33.      strmWriter.Write(str2);
  34.      strmWriter.Write(str);
  35.      strmWriter.Write(str3);
  36.      strmWriter.WriteLine(); //換行
  37. }
  38. strmWriter.Flush();
  39. strmWriter.Close();
  40. if (con.State == ConnectionState.Open)
  41. {
  42.      con.Close();
  43. }
複製代碼

 

C#讀取EXCEL檔案的三種經典方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.