EXCEL导出至服务器指定位置
新手刚接触.net,现在需要把GridView的内容存在excel后保存在服务器指定位置,在网上找到了ToExcel函数,实现了将GridView的内容复制到excel,可是是将excel保存到客户端,会有小框 【打开】【保存】【取消】,怎么能实现将excel保存在服务器指定位置?新手求指教。
private void ToExcel(Control ctl, string FileName)
{
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
[解决办法]
客户端操作文件保存到服务器指定位置。
项目中写的 LZ可以稍微改下!
string dirpath = "D:\\....";//物理路径
if (Directory.Exists(dirpath) == false)//确定给定路径是否引用磁盘上的现有目录。
{
Directory.CreateDirectory(dirpath);
}
Random ro = new Random();//随机数生成器
int name = 1;
for (int i = 0; i < files.Count; i++)
{
System.Web.HttpPostedFile myFile = files[i];
string FileName = "";
string FileExtention = "";
FileName = System.IO.Path.GetFileName(myFile.FileName);//返回指定路径字符串的文件名和扩展名。
string stro = ro.Next(100, 100000000).ToString() + name.ToString();//产生一个随机数用于新命名的文件
string NewName = DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + stro;
if (FileName.Length > 0)//有文件才执行上传操作再保存到数据库
{
FileExtention = System.IO.Path.GetExtension(myFile.FileName);
string ppath = dirpath + @"\" + NewName + FileExtention;
myFile.SaveAs(ppath);//保存上载文件的内容。
}
name = name + 1;//用来重命名规则的变量
}
}
[解决办法]
以下是我用的,
//ds是查询到的
string serverpath = Server.MapPath("~/Excel/" + filename);
String strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=2'", serverpath);
OleDbConnection Excel_conn = new OleDbConnection(strConnectionString);
Excel_conn.Open();
for (int i = 0; i < ds.Tables["data_table"].Rows.Count; i++)//把查询到的数据插入模板中
{
string theme = ds.Tables["data_table"].Rows[i]["theme"].ToString();
theme = theme.Substring(theme.LastIndexOf("-") + 1);
string intostr = "insert into [Sheet1$] (F1,F2,F3,F4,F5)values(" + "'" + ds.Tables["data_table"].Rows[i]["name"].ToString() + "'" + "," + "'" + ds.Tables["data_table"].Rows[i]["teach_subject"].ToString() + "'" + "," + "'"
+ ds.Tables["data_table"].Rows[i]["class"].ToString() + "'" + "," + "'" + theme + "'" + "," + "'" + ds.Tables["data_table"].Rows[i]["send_time"].ToString() + "'" + ")";
OleDbCommand cm = new OleDbCommand(intostr, Excel_conn);
cm.ExecuteNonQuery();//插入数据
}
Excel_conn.Close();
Excel_conn.Dispose();