Opening a client-side Excel file using EPPlus

末鹿安然 提交于 2019-12-06 13:01:45

问题


I am the middle of writing a program which has to create an excel file on a client machine and then, after they have saved and updated it then I need to import it again and apply the changes to my database. The export bit of it works fine, however when I import from the web application I get zero worksheets in my workbook. If I run it on my development machine, i.e. the website is running on the same machine as the file is located then it works fine.

My code is as follows:

try
    {
        Productsfile = new FileInfo(PathandFileName);
    }
    catch (Exception ex)
    {
        lblStatus.Text = string.Format("Error getting file info {0}", ex.Message);
        return;
    }

    lblStatus.Text += "File Opened succesfully " + Productsfile.FullName + Environment.NewLine;

    //Open and read file
    try
    {
        using (ExcelPackage datafile = new ExcelPackage(Productsfile))
        {

            ExcelWorkbook wkb = datafile.Workbook;


            if (wkb != null)
            {

                lblStatus.Text += string.Format("The workbook is not null and there are {0} worksheets", wkb.Worksheets.Count) + Environment.NewLine;

I have confirmed that the code gets to the last label update, which tells me there are zero worksheets in the workbook, but importantly that the workbook itself is not null.

When we created the export the following code was used, which transfers the data stream from server to client - I am wondering if something to reverse it is needed:

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=Products.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
        Response.End();

回答1:


Right, I believe I've found the answer:

1) Get the file details from a fileupload control 2) Convert this to a memory stream 3) Create the package using the memory stream

And the code is as follows:

if (FileUpload1.HasFile)
        {

            HttpPostedFile file = Request.Files[0];
            myLabel.Text = file.FileName;
            MemoryStream mem = new MemoryStream();
            mem.SetLength((int)file.ContentLength);

            file.InputStream.Read(mem.GetBuffer(), 0, (int)file.ContentLength);

            ExcelPackage package = new ExcelPackage(mem);


            ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
            myLabel.Text += " " + worksheet.Name;

        }


来源:https://stackoverflow.com/questions/17955325/opening-a-client-side-excel-file-using-epplus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!