引用:
using System.Data;
using System.Data.OleDb;
using Microsoft.Office.Interop.Excel;
using DataTable = System.Data.DataTable;
using Excel = Microsoft.Office.Interop.Excel;
gridview值获取:
标题:GridView1.HeaderRow.Cells[0].Text
正文: GridView1.Rows[0].Cells[0].Text
table使用:
DataTable mydt = createDataSource(fullpath);
行列获取:mydt.Rows[2][2].ToString()
标题获取:mydt.Columns[0].Caption.ToString()
读取代码:
string fullpath = @"C:\Users\Administrator\Desktop\工作簿1.xlsx";
Excel.Application excel = new Excel.Application();
excel.Workbooks.Open(fullpath);
DataTable mydt = createDataSource(fullpath);
GridView1.DataSource = mydt;
GridView1.DataBind();
excel.Workbooks.Close();
//Response.Write(mydt.Columns[0].Caption.ToString());//3
//GridView1.DataSource = null; DataBind();//重新初始化
for (int j = 0; j <= mydt.Columns.Count - 1;j++)//列赋值
{
for (int i= 0; i <= mydt.Rows.Count - 1; i++)//行赋值
{
//Response.Write(mydt.Rows.Count );//11
//Response.Write(mydt.Columns.Count );//3
//GridView1.Rows[i].Cells[j].Text = mydt.Rows[i][j].ToString();
//GridView1.HeaderRow.Cells[j].Text = mydt.Columns[j].Caption.ToString();
}
}
事件方法:
private DataTable createDataSource(string strPath)
{
string ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
OleDbConnection myCon = new OleDbConnection(ConnStr);
myCon.Open();
//执行查询
String strSql = "select * from [sheet1$]";
OleDbCommand myCom = new OleDbCommand(strSql, myCon);
OleDbDataAdapter myda = new OleDbDataAdapter(myCom);
DataSet myds = new DataSet();
myda.Fill(myds);
return myds.Tables[0];
}
选择上传文件并调用加载:
//string gv_txt = GridView1.Rows[0].Cells[0].Text;
//Response.Write(gv_txt);
string _targPath="";
if (FileUpload1.HasFile)
{
_targPath = MapPath("~/App_Data/") + FileUpload1.FileName;
FileUpload1.SaveAs(_targPath);
//Response.Redirect(Request.RawUrl);//重新定位页面
}
//Response.Write(_targPath);
if (System.IO.File.Exists(_targPath))
{
string fullpath = _targPath;
Excel.Application excel = new Excel.Application();
excel.Workbooks.Open(_targPath);
DataTable mydt = createDataSource(_targPath);
GridView1.DataSource = mydt;
GridView1.DataBind();
excel.Workbooks.Close();
//Response.Write("<script language=javascript>alert('请再次上传');</" + "script>");
}
else
{
Response.Write("<script language=javascript>alert('请再次上传');</" + "script>");
}