当前位置: 移动技术网 > IT编程>开发语言>.net > .NET读取Excel文件的三种方法的区别

.NET读取Excel文件的三种方法的区别

2017年12月12日  | 移动技术网IT编程  | 我要评论
asp.net读取excel文件方法一:采用oledb读取excel文件: 把excel文件当做一个数据源来进行数据的读取操作,实例如下: 复制代码 代码如下:publ

asp.net读取excel文件方法一:采用oledb读取excel文件:

把excel文件当做一个数据源来进行数据的读取操作,实例如下:

复制代码 代码如下:

public dataset exceltods(string path)  
{   
  string strconn = "provider=microsoft.jet.oledb.4.0;" +"data source="+ path +";"+"extended properties=excel 8.0;";
   oledbconnection conn = new oledbconnection(strconn);   
  conn.open();
   string strexcel = "";
   oledbdataadapter mycommand = null;
   dataset ds = null;
   strexcel="select * from [sheet1$]";
   mycommand = new oledbdataadapter(strexcel, strconn);
   ds = new dataset();    mycommand.fill(ds,"table1");
   return ds;
}

对于excel中的表即sheet([sheet1$])如果不是固定的可以使用下面的方法得到

复制代码 代码如下:

string strconn = "provider=microsoft.jet.oledb.4.0;" +"data source="+ path +";"+"extended properties=excel 8.0;";
oledbconnection conn = new oledbconnection(strconn);
datatable schematable = objconn.getoledbschematable(system.data.oledb.oledbschemaguid.tables,null);
string tablename=schematable.rows[0][2].tostring().trim();  

另外:也可进行写入excel文件,实例如下:

复制代码 代码如下:

public void dstoexcel(string path,dataset oldds)   {   
//先得到汇总excel的dataset 主要目的是获得excel在dataset中的结构   
string strcon = " provider = microsoft.jet.oledb.4.0 ; data source ="+path1+";extended properties=excel 8.0" ;
oledbconnection myconn = new oledbconnection(strcon) ;
string strcom="select * from [sheet1$]";
myconn.open ( ) ;
oledbdataadapter mycommand = new oledbdataadapter ( strcom, myconn ) ;
ystem.data.oledb.oledbcommandbuilder builder=new oledbcommandbuilder(mycommand);   
//quoteprefix和quotesuffix主要是对builder生成insertcomment命令时使用。   
builder.quoteprefix="[";     //获取insert语句中保留字符(起始位置)
builder.quotesuffix="]"; //获取insert语句中保留字符(结束位置) 
dataset newds=new dataset();
mycommand.fill(newds ,"table1") ;
for(int i=0;i<oldds.tables[0].rows.count;i++)   
{    
  //在这里不能使用importrow方法将一行导入到news中,
  //因为importrow将保留原来datarow的所有设置(datarowstate状态不变)。
  //在使用importrow后newds内有值,但不能更新到excel中因为所有导入行的datarowstate!=added
  datarow nrow=adataset.tables["table1"].newrow();
   for(int j=0;j<newds.tables[0].columns.count;j++)
   {     
    nrow[j]=oldds.tables[0].rows[i][j];
   }    
    newds.tables["table1"].rows.add(nrow);  
}   
mycommand.update(newds,"table1");
myconn.close();
}

asp.net读取excel文件方法二:引用的com组件:microsoft.office.interop.excel.dll读取excel文件

首先是excel.dll的获取,将office安装目录下的excel.exe文件copy到dotnet的bin目录下,cmd到该目录下,运行 tlbimp excel.exe excel.dll 得到dll文件。

在项目中添加引用该dll文件.

复制代码 代码如下:

//读取excel的方法   (用范围区域读取数据)
private void openexcel(string strfilename)  {     
object missing = system.reflection.missing.value;     
application excel = new application();//lauch excel application
if (excel == null)    
{       
  response.write("<script>alert('can't access excel')</script>");     
}    
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(); 
}

asp.net读取excel文件方法三:将excel文件转化成csv(逗号分隔)的文件,用文件流读取(等价就是读取一个txt文本文件)。

先引用命名空间:

复制代码 代码如下:

using system.text;和using system.io;           
filestream fs = new filestream("d:\\customer.csv", filemode.open, fileaccess.read, fileshare.none);
streamreader sr = new streamreader(fs, system.text.encoding.getencoding(936));
string str = "";           
string s = console.readline();           
while (str != null)           
{   
  str = sr.readline();
  string[] xu = new string[2];
  xu = str.split(',');
  string ser = xu[0];
  string dse = xu[1];
  if (ser == s)
  { 
    console.writeline(dse);break;
  }          
}  
sr.close();

另外也可以将数据库数据导入到一个txt文件,实例如下:

复制代码 代码如下:

//txt文件名 
string fn = datetime.now.tostring("yyyymmddhhmmss") + "-" + "po014" + ".txt";   oledbconnection con = new oledbconnection(constr);   con.open();  string sql = "select  item,reqd_date,qty,pur_flg,po_num from tsd_po014";          oledbcommand mycom = new oledbcommand("select * from tsd_po014", mycon); 
//oledbdatareader myreader = mycom.executereader();  //也可以用reader读取数据
dataset ds = new dataset(); 
oledbdataadapter oda = new oledbdataadapter(sql, con);
oda.fill(ds, "po014"); 
datatable dt = ds.tables[0]; 
filestream fs = new filestream(server.mappath("download/" + fn), filemode.create, fileaccess.readwrite); 
streamwriter strmwriter = new streamwriter(fs);    //存入到文本文件中   
//把标题写入.txt文件中 
//for (int i = 0; i <dt.columns.count;i++) 
//{ 
//    strmwriter.write(dt.columns[i].columnname + "  ");
//} 
foreach (datarow dr in dt.rows) 
{    
  string str0, str1, str2, str3;     
  string str = "|";  //数据用"|"分隔开   
  str0 = dr[0].tostring();     
  str1 = dr[1].tostring();   
  str2 = dr[2].tostring(); 
  str3 = dr[3].tostring();  
   str4 = dr[4].tostring().trim();  
   strmwriter.write(str0);  
   strmwriter.write(str); 
   strmwriter.write(str1);  
   strmwriter.write(str); 
   strmwriter.write(str2);  
   strmwriter.write(str);  
   strmwriter.write(str3); 
   strmwriter.writeline();  //换行 

strmwriter.flush();
strmwriter.close();
if (con.state == connectionstate.open) 
{    
  con.close();
}

asp.net读取excel文件的方法就向你介绍到这里,希望对你了解asp.net读取excel文件有所帮助。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网