类中代码:
/// <summary>
/// 读取Excel表格数据,返回数据集DataSet
/// </summary>
/// <param name="FileName">文件名</param>
/// <returns>dataset</returns>
public DataSet GetExcelData(string FileName)
{
///建立连接,读取表格中的数据
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =D:\\Temp\\" + FileName + ";Extended Properties=Excel 8.0";///建立连接,地址为str传递的地址
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = " SELECT * FROM [Sheet1$]";///SQL操作语句,就是说:取得所有数据从Sheet1
myConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
DataSet myDataSet = new DataSet();///建立新的数据集myDataSet
myCommand.Fill(myDataSet, "[Sheet1$]");///填充数据集
myConn.Close();
//columnNum = myDataSet.Tables[0].Columns.Count;///读取列数并赋值给columnNum
//rowNum = myDataSet.Tables[0].Rows.Count;///读取行数并赋值给rowNum
//resultRowNum = columnNum - 1;///读取结果行数(实际上就是去掉第一列编号列的列数,我的程序中将结果显示横置了)
return myDataSet;
}
/// 读取Excel表格数据,返回数据集DataSet
/// </summary>
/// <param name="FileName">文件名</param>
/// <returns>dataset</returns>
public DataSet GetExcelData(string FileName)
{
///建立连接,读取表格中的数据
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =D:\\Temp\\" + FileName + ";Extended Properties=Excel 8.0";///建立连接,地址为str传递的地址
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = " SELECT * FROM [Sheet1$]";///SQL操作语句,就是说:取得所有数据从Sheet1
myConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
DataSet myDataSet = new DataSet();///建立新的数据集myDataSet
myCommand.Fill(myDataSet, "[Sheet1$]");///填充数据集
myConn.Close();
//columnNum = myDataSet.Tables[0].Columns.Count;///读取列数并赋值给columnNum
//rowNum = myDataSet.Tables[0].Rows.Count;///读取行数并赋值给rowNum
//resultRowNum = columnNum - 1;///读取结果行数(实际上就是去掉第一列编号列的列数,我的程序中将结果显示横置了)
return myDataSet;
}
后台代码:
protected void btnshowexcel_Click(object sender, EventArgs e)
{
try
{
this.FileUpload1.SaveAs("D:\\Temp\\" + FileUpload1.FileName);
DataSet ds = lh.GetExcelData(FileUpload1.FileName);
string excelname = FileUpload1.FileName;
HiddenField1.Value = excelname;
GridView1.DataSource = ds;
GridView1.DataBind();
btnshowexcel.Enabled = false;
btnAddexcel.Visible = true;
}
catch
{
Response.Write("<script>alert('查看失败!请检查路径是否正确!');</script>");
}
}
{
try
{
this.FileUpload1.SaveAs("D:\\Temp\\" + FileUpload1.FileName);
DataSet ds = lh.GetExcelData(FileUpload1.FileName);
string excelname = FileUpload1.FileName;
HiddenField1.Value = excelname;
GridView1.DataSource = ds;
GridView1.DataBind();
btnshowexcel.Enabled = false;
btnAddexcel.Visible = true;
}
catch
{
Response.Write("<script>alert('查看失败!请检查路径是否正确!');</script>");
}
}
其中由于需要在另一个按钮事件里导入到数据库,用HiddenField控件轻松存储了一个变量值。
这个控件太帅啦~~~~~~~~
爽爽师姐在我旁边做图片设计,想的“头破血流”呢~~~~嘿嘿!!!
想想自己有问题能找老朱帮忙解决,真太幸福了。
就上面的几个问题要没朱哥光凭自己想指不定弄到什么时候呢~~~~~~~~~
真开心:)
有问题找百度,百度没有找老朱。
嘿嘿!比师姐在一边默默设计幸福多啦~~~~