日期:2014-05-17  浏览次数:20532 次

如何导出Excel,不保存在服务器上,直接弹出保存对话框保存在本地?
public void ExportToExcel(HttpResponse resp, string fileName,ObjectDataSource odsMain)
  {  
  Application xlApp = new Application();
  if (xlApp == null)
  {
  return;
  }

  System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
  System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
  Workbooks workbooks = xlApp.Workbooks;
  Workbook workbook = workbooks.Add();
  Worksheet worksheet = (Worksheet)workbook.ActiveSheet;
  worksheet.Name = fileName;
  Range range;

  string[] columnName = new string[12];
  columnName[0] = "终端编号";
  columnName[1] = "终端名称";
  columnName[2] = "交易日期";


  //将表头写入Excel
  for (int i = 0; i < 3; i++)
  {
  worksheet.Cells[1, i + 1] = columnName[i];
  range = (Range)worksheet.Cells[1, i + 1];
  //range.Interior.ColorIndex = 10;
  range.Font.Bold = true;
  range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
  }

xlApp.DisplayAlerts = false;
  try
  {
  resp.Clear();
  resp.Buffer = true;
  resp.Charset = "GB2312";
  resp.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", fileName));
  resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
  resp.ContentType = "application/msexcel";//设置输出文件类型为txt文件。 
  this.EnableViewState = false;
  System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
  System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
  resp.Write();
  resp.End();
  }
  catch(Exception e)
  {
  FunctionMessage = e.Message;
  ExceptionMessage = e.ToString();
  Log(e.ToString());
  return;
  }
  finally
  {
  workbook.Close(Type.Missing, Type.Missing, Type.Missing);
  workbooks.Close();
  xlApp.Quit();
  System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
  System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
  workbook = null;
  xlApp = null;
  GC.Collect();
  }
  }

这是我的导出到Excel函数,我的代码有问题吗?红色部分的参数应该是什么?
我想要的效果:程序在服务器上,我在客户端中访问,点击导出按钮可以弹出保存框选择路径,保存在本地,而服务器上不弹出保存框,也不保存。

------解决方案--------------------
要下载得传二进制流

context.Response.BinaryWrite( );
------解决方案--------------------
传二进制流就行了啦
------解决方案--------------------
汗。。。干嘛不用水晶报表等一些报表软件导出。。。简单又灵活。。。