操作excel的例子
private void SaveToExcel()
{

string urlPath = HttpContext.Current.Request.ApplicationPath + "/Temp/";

string physicPath = HttpContext.Current.Server.MapPath(urlPath);

string fileName = Guid.NewGuid() + ".Xls";

string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + physicPath + fileName +";Extended Properties=Excel 8.0;";

OleDbConnection objConn = new OleDbConnection(connString);
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = objConn;
objConn.Open();



//建立表结构

objCmd.CommandText = @"CREATE TABLE TBL_Customer (CustomerName varchar,CustomerNo varchar)";

objCmd.ExecuteNonQuery();

objCmd.CommandText = "INSERT INTO TBL_Customer(CustomerName, CustomerNo) VALUES ('毛小华', 'good')";

objCmd.ExecuteNonQuery();

//提供下载

objCmd.Dispose();
objConn.Dispose();

HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.WriteFile(physicPath + fileName);
string httpHeader="attachment;filename=backup.Xls";
response.AppendHeader("Content-Disposition", httpHeader);
response.Flush();

System.IO.File.Delete(physicPath + fileName);//删除临时文件
response.End();
}
{
string urlPath = HttpContext.Current.Request.ApplicationPath + "/Temp/";
string physicPath = HttpContext.Current.Server.MapPath(urlPath);
string fileName = Guid.NewGuid() + ".Xls"; 
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + physicPath + fileName +";Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(connString);
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = objConn;
objConn.Open();


//建立表结构
objCmd.CommandText = @"CREATE TABLE TBL_Customer (CustomerName varchar,CustomerNo varchar)";
objCmd.ExecuteNonQuery();
objCmd.CommandText = "INSERT INTO TBL_Customer(CustomerName, CustomerNo) VALUES ('毛小华', 'good')";
objCmd.ExecuteNonQuery();
//提供下载
objCmd.Dispose();
objConn.Dispose();

HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.WriteFile(physicPath + fileName);
string httpHeader="attachment;filename=backup.Xls";
response.AppendHeader("Content-Disposition", httpHeader);
response.Flush();
System.IO.File.Delete(physicPath + fileName);//删除临时文件
response.End();
}

浙公网安备 33010602011771号