日期:2014-05-18 浏览次数:20415 次
private const string strConn = "自己写连接字符串"; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindDataToGridView(); } } /// <summary> /// 绑定 /// </summary> private void BindDataToGridView() { SqlConnection conn = new SqlConnection(strConn); string strSQL = "select * from [User]"; SqlDataAdapter da = new SqlDataAdapter(strSQL, conn); DataSet ds = new DataSet(); da.Fill(ds, "[User]"); this.GridView1.DataSource = ds; this.GridView1.DataKeyNames = new string[] { "UserId" }; this.GridView1.DataBind(); } /// <summary> /// 导出DataSet到Execl /// </summary> private void OutExecl() { Excel.Application myExcel = new Excel.Application(); myExcel.Visible = true; if (myExcel == null) { Page.RegisterStartupScript("", "<script>alert('EXCEL无法启动');</script>"); } Workbook work = myExcel.Application.Workbooks.Add(Type.Missing); Worksheet sheet = (Worksheet)work.Worksheets[1]; int rowCount = 0; int columnCount = 0; columnCount = this.GridView1.Columns.Count; rowCount = this.GridView1.Rows.Count; rowCount--; for (int m = 1; m < columnCount; m++) { sheet.Cells[1, m] = this.GridView1.Columns[m].HeaderText;//得到列标题文本 } for (int i = 0; i <= rowCount; i++) //二维表填充从每一行开始 { for (int j = 1; j < columnCount; j++) //填充每一行第j列单元格,循环添加行列数据 { sheet.Cells[i + 2, j] = this.GridView1.Rows[i].Cells[j].Text; } } Page.RegisterStartupScript("", "<script>alert('成功导出!');</script>"); } /// <summary> /// 导出 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnOut_Click(object sender, EventArgs e) { OutExecl(); } /// <summary> /// 导入Excel到DataSet /// </summary> /// <param name="filePath"></param> /// <returns></returns> private DataSet InExecl(string filePath) { DataSet ds = new DataSet(); string connStr = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\""; OleDbConnection myConn = new OleDbConnection(connStr); string strSQL = " SELECT * FROM [Sheet1$]"; myConn.Open(); OleDbDataAdapter myCommand = new OleDbDataAdapter(strSQL, myConn); DataSet myDataSet = new DataSet(); myCommand.Fill(myDataSet, "[Sheet1$]"); myConn.Close(); return myDataSet; } /// <summary> /// 导入 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnIn_Click(object sender, EventArgs e) { DataSet ds = InExecl(this.File1.PostedFile.FileName); this.GridView2.DataSource = ds; this.GridView2.DataBind(); } }
------解决方案--------------------
private static DataSet NewMethod(string ExcelName, string Sheet)
{
DataSet dsE = new DataSet();
string MyConnectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @System.Web.HttpContext.Current.Server.MapPath("ExcelTemp") + @"\" + ExcelName+ "