logo

使用 ADO.NET 更新 Excel 中指定单元格的内容

作者:孟宪会 阅读:2022 发表于:2011-01-19 16:39:43

需要注意是:1,IMEX必须设置为2;2,该列的数据类型最好要一致。下面的例子更新B11单元格的内容。 

ASPX 代码
<%@ Page Language="C#" Debug="true" %>

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<script runat="server">
  
  String ConnectionString
= String.Empty;
  protected
void Page_Load(object sender, EventArgs e)
  {
    ConnectionString
= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("excel.xls") + ";Extended Properties='Excel 8.0;HDR=No;IMEX=2;'";
    
if (!IsPostBack)
    {
      DataBindExcel();
    }
  }

  protected
void UpDate_Click(object sender, EventArgs e)
  {
    using (OleDbConnection cn
= new OleDbConnection(ConnectionString))
    {
      cn.Open();
      String sql
= "UPDATE [Sheet1$B11:B11] SET F1 = '" + DateTime.Now.ToString() + "'";
      OleDbCommand cmd
= new OleDbCommand(sql, cn);
      cmd.ExecuteNonQuery();
      cn.Dispose();
    }
    Response.Redirect(Request.UrlReferrer.ToString());
  }

  private
void DataBindExcel()
  {
    using (OleDbConnection cn
= new OleDbConnection(ConnectionString))
    {
      cn.Open();
      String sql
= "select * FROM [Sheet1$]";
      OleDbCommand cmd
= new OleDbCommand(sql, cn);
      GridView1.DataSource
= cmd.ExecuteReader();
      GridView1.DataBind();
      cn.Dispose();
    }
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
  
<form id="form1" runat="server">
  
<asp:GridView ID="GridView1" runat="server">
  
</asp:GridView>
  
<asp:Button ID="UpDate" Text="更新数据为当前日期" runat="server" OnClick="UpDate_Click" />
  
</form>
</body>
</html>