Write to Excel file hosted on Sharepoint 2016 using EPPlus (C#)

和自甴很熟 提交于 2020-06-13 10:02:06

问题


I'm trying for many days to write to an excel file without success.

The file is hosted on a sharepoint 2016 site which I am the administrator. I can read all the sheets of the file without any problem. But when I try to load it to an ExcelPackage variable, it seems, the stream length is 0.

You have details of what happening in the code comments. Do you have any idea of what I'm doing wrong ??

Any help will be appreciated. Here is the code :

public static ClientContext clientContext;
private static File dbFile;

public static void AddLine(string sheetName, ImputationLine newData)
{
    try
    {
        if (dbFile is null)
            LoadDb();

        ClientResult<IO.Stream> fileStream = dbFile.OpenBinaryStream();
        clientContext.Load(dbFile);
        clientContext.ExecuteQuery();

        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

        using (var package = new ExcelPackage())
        {
            using (IO.MemoryStream mStream = new IO.MemoryStream())
            {
                if (fileStream != null)
                {
                    fileStream.Value.CopyTo(mStream); // mStream is well populated with data from fileStream
                    package.Load(mStream); //No exception here but package.File is null, package.Stream.Length = 0

                    ExcelWorksheet worksheet = package.Workbook.Worksheets[sheetName]; //package.Workbook.Worksheets.Count = 0

                    int rowIndex = worksheet.Dimension.End.Row + 1;
                    for (int i = 0; i < newData.Values.Count; i++)
                    {
                        worksheet.Cells[rowIndex, i].Value = newData.Values[i];
                    }
                    package.Save();
                }
            }
        }

    }
    catch (Exception e)
    {
        throw e;
    }
}

private static void LoadDb()
{
    string subFolder = ConfigurationManager.AppSettings["SubFolder"];
    string dbFileName = ConfigurationManager.AppSettings["DbFileName"];
    List list = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["SpLibName"]);
    clientContext.Load(list.RootFolder);
    clientContext.ExecuteQuery();
    FileServerRelativeUrl = list.RootFolder.ServerRelativeUrl + subFolder + dbFileName;
    dbFile = clientContext.Web.GetFileByServerRelativeUrl(FileServerRelativeUrl);
}

Thank's for your replies !!

来源:https://stackoverflow.com/questions/62117472/write-to-excel-file-hosted-on-sharepoint-2016-using-epplus-c

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