压缩上传及导出csv文件

  #region 压缩
        public static void RARsave(string patch, string rarPatch, string rarName)
        {
            String the_rar;
            RegistryKey the_Reg;
            Object the_Obj;
            String the_Info;
            ProcessStartInfo the_StartInfo;
            Process the_Process;
            try
            {
                the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command");
                the_Obj = the_Reg.GetValue("");
                the_rar = the_Obj.ToString();
                the_Reg.Close();
                the_rar = the_rar.Substring(1, the_rar.Length - 7);
                Directory.CreateDirectory(patch);
                //命令参数
                the_Info = " a    " + rarName + "  " + patch + "  -r"; ;
                the_StartInfo = new ProcessStartInfo();
                the_StartInfo.FileName = the_rar;
                the_StartInfo.Arguments = the_Info;
                the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                //打包文件存放目录
                the_StartInfo.WorkingDirectory = rarPatch;
                the_Process = new Process();
                the_Process.StartInfo = the_StartInfo;
                the_Process.Start();
                the_Process.WaitForExit();
                the_Process.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

 

 

 

    #region  上传FTP
        static string ftpServerIP = ConfigurationManager.AppSettings["FtpServerIP"].ToString();
        static string ftpUserID = ConfigurationManager.AppSettings["FtpUserID"].ToString();
        static string ftpPassword = ConfigurationManager.AppSettings["FtpPassword"].ToString();

        static FtpWebRequest reqFTP;
        private static void Connect(String path)//连接ftp
        {
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        }
        public static void Upload(string filename) //上面的代码实现了从ftp服务器上载文件的功能
        {
            FileInfo fileInf = new FileInfo(filename);
            string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            Connect(uri);
            reqFTP.KeepAlive = false;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.ContentLength = fileInf.Length;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
               // MessageBox.Show(ex.Message, "Upload Error");
            }
        }


        #endregion

 

 

 #region 导出csv
        public static void ExportToSvc(System.Data.DataTable dt, string FilePath, string strFileName)
        {
            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }
            if (File.Exists(FilePath + strFileName))
            {
                File.Delete(FilePath + strFileName);
            }
            StringBuilder strColu = new StringBuilder();
            StringBuilder strValue = new StringBuilder();
            int i = 0;
            try
            {
                string Path = FilePath + strFileName;
                StreamWriter sw = new StreamWriter(new FileStream(Path, FileMode.CreateNew), Encoding.GetEncoding("GB2312"));

                for (i = 0; i <= dt.Columns.Count - 1; i++)
                {
                    strColu.Append(dt.Columns[i].ColumnName);
                    strColu.Append(",");
                }
                strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符
                sw.WriteLine(strColu);
                foreach (DataRow dr in dt.Rows)
                {
                    strValue.Remove(0, strValue.Length);
                    for (i = 0; i <= dt.Columns.Count - 1; i++)
                    {
                        strValue.Append(dr[i].ToString());
                        strValue.Append(",");
                    }
                    strValue.Remove(strValue.Length - 1, 1);
                    sw.WriteLine(strValue);
                }

                sw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            // System.Diagnostics.Process.Start(strPath);
        }
        #endregion

 

 

 

public void OutPutExcel()
        
{
            
//定义文档类型、字符编码
            Response.Clear();
          Response.Buffer
= true;
          Response.Charset
="GB2312";
            
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
          
//filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc    .xls    .txt   .htm
          Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls");
          Response.ContentEncoding
=System.Text.Encoding.GetEncoding("GB2312");
          
//Response.ContentType指定文件类型 可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html 或其他浏览器可直接支持文档
          Response.ContentType = "application/ms-excel";
          
this.EnableViewState = false;
            
// 定义一个输入流
          System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
          System.Web.UI.HtmlTextWriter oHtmlTextWriter 
= new System.Web.UI.HtmlTextWriter(oStringWriter);

            
this.RenderControl(oHtmlTextWriter);
          
//this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件
          Response.Write(oStringWriter.ToString());
          Response.End();
        }


 

 

 /// <summary>
  /// 导出文件
  /// </summary>
  /// <param name="body"></param>
  /// <param name="type"></param>
  ///
  public static void ToDocument(System.Web.UI.Control body,string type,string filename)
  {
   string fileType = "application/ms-excel";  //文件类型

   //转换用户输入的type,全部为大写防止选择失败
   type = type.ToUpper().Trim();

   switch(type)
   {
    case "EXCEL":
    {
     filename+=".xls";
     fileType = "application/ms-excel";
     break;
    }
    case "WORD":
    {
     filename+=".doc";
     fileType = "application/ms-word";
     break;
    }
    case "JPEG":
    {
     filename+=".jpeg";
     fileType = "image/JPEG";
     break;
    }
    case "GIF":
    {
     filename+=".gif";
     fileType = "image/GIF";
     break;
    }
    case "HTML":
    {
     filename+=".html";
     fileType = "text/HTML";
     break;
    }
    case "CSV":
    {
     filename+=".csv";
     fileType = "application/octet-stream";
     break;
    }
    case "TXT":
    {
     filename+=".txt";
     fileType = "text/plain";
     break;
    }
   }
   //清除Response缓存内容
   HttpContext.Current.Response.Clear();
   HttpContext.Current.Response.Buffer= true;

   //确定字符的编码格式
   HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(filename));
   HttpContext.Current.Response.ContentType = fileType;
   HttpContext.Current.Response.Charset ="GB2312";
   HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.GetEncoding("GB2312");

   try
   {
    body.Page.EnableViewState = false;
   }
   catch
   {}

   //表体空间
   System.IO.StringWriter swBody = new System.IO.StringWriter() ;
   System.Web.UI.HtmlTextWriter hwBody = new System.Web.UI.HtmlTextWriter (swBody);
   body.RenderControl(hwBody);

   //消除乱码特别设定,非常规方法
   string strExcel = "" ;
   strExcel = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">";
   strExcel += hwBody.InnerWriter.ToString();

   HttpContext.Current.Response.Write(strExcel);
   HttpContext.Current.Response.End();
  }

 

 

 

posted on 2012-04-05 17:26  jameshappy  阅读(684)  评论(0编辑  收藏  举报