protected void btnPrn_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet("gv");//new一个标视为 gv的库
DataTable dt = new DataTable("logoo"); string sCmd = "select * from mytable "; MySqlDataReader reader;
mySqlMod newMySqlMod = new mySqlMod();
newMySqlMod.RunSQL(sCmd, out reader);
dt.Load(reader); string FileName ="test.xls";//前为固定名称,后为随机名称 Guid.NewGuid().ToString() + ".xls";
//增加服务发布地址 string sNewFullFile = Server.MapPath(FileName);
try
{
//此种方法必须在发布地址预先放置一个format.xls模板 File.Copy(Server.MapPath("format.xls"), sNewFullFile);
if (File.Exists(sNewFullFile))
File.Delete(sNewFullFile);
}
catch (Exception er)
{
Response.Write(er.Message);
return;
} String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+ sNewFullFile + ";" + "Extended Properties=Excel 8.0;";
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strConn);
OleDbCommand cmd = null;
bool bRet = false;
try
{
conn.Open();
cmd = new OleDbCommand("create table [sheet1]([ID] int,[字段一] Text,[字段二] Text,[字段三] Text)", conn);
cmd.ExecuteNonQuery();
string strSQL = "INSERT INTO [Sheet1$] ([ID], [字段一],[字段二],[字段三]) VALUES (?, ?, ?, ?)";
cmd = new OleDbCommand(strSQL, conn);
for (int i = 0; i < 4; i++)
{
cmd.Parameters.Add(i.ToString(), OleDbType.VarChar);
}
DataView dv = dt.DefaultView;
foreach (DataRowView row in dv)
{
cmd.Parameters[0].Value = (int)row["id"];
cmd.Parameters[1].Value = row["col1"].ToString();
cmd.Parameters[2].Value = row["col2"].ToString();
cmd.Parameters[3].Value = row["col3"].ToString(); cmd.ExecuteNonQuery();
}
bRet = true;
}
catch (Exception er)
{
Response.Write(er.Message);
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
conn.Dispose();
}
if (bRet)
Response.Redirect(FileName);
}
温馨提示:答案为网友推荐,仅供参考