求解ADO.NET导出EXCEL(指定单元格)
#region 导出excel
// 根据模板文件创建副本
string name = DateTime.Now.ToString("yyyyMMddhhmmss");
string webPath = string.Format("~/xlsTemplate/{0}.xls", name);
string filePath = Server.MapPath(webPath);
File.Copy(Server.MapPath("~/xlstemp/train.xls"), filePath);
// 使用OleDb驱动程序连接到副本
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=NO\"");
using (conn)
{
conn.Open();
//// 增加记录
//foreach (DataRow item in ds.Tables[0].Rows)
//{
OleDbCommand cmd = new OleDbCommand("UPDATE [Sheet1$] SET B2='Aaron'", conn);
cmd.ExecuteNonQuery();
cmd.Dispose();
//}
}
// 输出副本的二进制字节流
Response.Clear();
Response.ContentType = "application/ms-excel";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
Response.BinaryWrite(File.ReadAllBytes(filePath));
// 删除副本
File.Delete(filePath);
#endregion
******************************************************************
错误提示:至少一个参数没有被指定值。
难道不能直接操作单元格么?还是对XLS模板有特殊要求。希望各位前辈指点迷津。
[解决办法]
使用 ADO.NET 更新 Excel 中指定单元格的内容
需要注意是: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>