使用EPPlus库使用C#在FTP上直接创建Excel文件

时间:2018-06-25 13:29:20

标签: c# .net excel ftp epplus

我想在FTP服务器上创建一个Excel文件。我尝试在本地创建文件,该文件可以解决以下问题:如何在FTP而非本地驱动器中创建文件?

ExcelPkg.SaveAs(
  new FileInfo(@"C:\ExcelTest\" + DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx"))

我想直接在FTP中而不是在本地创建此文件,然后再移动它。

2 个答案:

答案 0 :(得分:2)

我必须对其进行2种不同的操作,首先创建Excel文件,然后上传现有文件,然后将其删除。 使用名为WinSCP的库 我找不到同时支持TLS隐式FTP和流API的支持90年代加密的任何库。因此,我无法在服务器上直接创建excel文件,而只能在本地临时创建该文件以将其复制并同时删除它,这几乎是我得到相同结果的同一件事。这是解决问题的方法

try
{
    // Setup session options
    SessionOptions sessionOptions = new SessionOptions
    {
        Protocol = Protocol.Ftp,
        HostName = @"xx.xx.x.x",
        UserName = "xxxx",
        Password = "xxxxxx",
        PortNumber = xxxx,
        FtpSecure = FtpSecure.Implicit, //Encryption protocol
        GiveUpSecurityAndAcceptAnyTlsHostCertificate = true // Accepts any certificate
    };

    using (Session session = new Session())
    {
        // Connect
        session.Open(sessionOptions);

        // Upload files
        TransferOptions transferOptions = new TransferOptions();
        transferOptions.TransferMode = TransferMode.Binary;

        TransferOperationResult transferResult;
        // Copy's Existing file to Connected server and delets the old one.
        // change by replace "true" with "false".
        transferResult =
            session.PutFiles(
                ExistingPath, "/ScheduleJobs/" + RemotePath, true, transferOptions);

        // Throw on any error
        transferResult.Check();

        // Print results
        foreach (TransferEventArgs transfer in transferResult.Transfers)
        {
            Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
            Console.ReadLine();
        }

    }

}
catch (Exception e)
{
    Console.WriteLine("Error: {0}", e);
}

答案 1 :(得分:1)

使用ExcelPackage.SaveAs overload that accepts a Stream并将FTP请求流传递给它,例如:
Upload a streamable in-memory document (.docx) to FTP with C#?


我现在无法测试EPPlus,但这应该可行:

WebRequest request = WebRequest.Create("ftp://ftp.example.com/remote/path/sheet.xlsx");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
using (Stream ftpStream = request.GetRequestStream())
{
    ExcelPkg.SaveAs(ftpStream);
}