ASP.NET读取Excel文件方法1

方法代码:

public DataSet ExcelToDS(string Path)
{
//定义EXCEL文件链接字符串
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";

//实例化OledConnection链接
OleDbConnection conn = new OleDbConnection(strConn);

//打开链接
conn.Open();

string strExcel = "";
OleDbDataAdapter myCommand
= null;
DataSet ds
= null;

//定义查询语句
strExcel = "select * from [sheet1$]";

//OledbdataAdaoter执行命令
myCommand = new OleDbDataAdapter(strExcel, strConn);

ds
= new DataSet();
//填充ds,并命名table1
myCommand.Fill(ds, "table1");

//关闭链接,释放文件
conn.Close();

return ds;
}
调用方法:(需要using System.Data.OleDb)
//test.xls 是excel文件名称
string strPath = Server.MapPath("test.xls");
DataSet ds
= ExcelToDS(strPath);

对于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();
}
posted @ 2011-07-07 14:14  hellowing  阅读(438)  评论(0)    收藏  举报