public void ReadExcel(string sExcelFile,GridView dgBom)
...{
DataTable ExcelTable;
DataSet ds = new DataSet();
//Excel的连接
OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sExcelFile + ";" + "Extended Properties=Excel 8.0;");
objConn.Open();
DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
string tableName = schemaTable.Rows[0][2].ToString().Trim();//获取 Excel 的表名,默认值是sheet1
string strSql = "select * from [" + tableName + "]";
OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
OleDbDataAdapter myData = new OleDbDataAdapter(strSql, objConn);
myData.Fill(ds, tableName);//填充数据
dgBom.DataSource =ds;
dgBom.DataBind();
objConn.Close();
ExcelTable = ds.Tables[tableName];
int iColums = ExcelTable.Columns.Count;//列数
int iRows = ExcelTable.Rows.Count;//行数
//定义二维数组存储 Excel 表中读取的数据
string[,] storedata = new string[iRows, iColums];
for(int i=0;i
...{
//将Excel表中的数据存储到数组
storedata[i, j] = ExcelTable.Rows[i][j].ToString();
}
}
参考用
strConn 是连接字符串
看你连接什么数据库。
access:connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\数据库名称.mdb"
Sql Server
connectionString="Data Source=localhost;Initial Catalog=数据库名称;User ID=用户名;Password=密码"