Code Monkey home page Code Monkey logo

epplus.core's Introduction

News

This project helped EPPlus to add .NET Core support. Please start using the original EPPlus. It supports .NETFramework 3.5, .NETFramework 4.0 & .NETStandard 2.0 now.


EPPlus.Core

EPPlus.Core is an unofficial port of the EPPlus library to .NET Core. It's based on the 5/24/2017, change set#fcded570d92e.

Install via NuGet

To install EPPlus.Core, run the following command in the Package Manager Console:

PM> Install-Package EPPlus.Core

You can also view the package page on NuGet.

Usage

Notes:

To run this project on non-Windows-based operating systems, you will need to install libgdiplus too:

  • Ubuntu 16.04 and above:
    • apt-get install libgdiplus
    • cd /usr/lib
    • ln -s libgdiplus.so gdiplus.dll
  • Fedora 23 and above:
    • dnf install libgdiplus
    • cd /usr/lib64/
    • ln -s libgdiplus.so.0 gdiplus.dll
  • CentOS 7 and above:
    • yum install autoconf automake libtool
    • yum install freetype-devel fontconfig libXft-devel
    • yum install libjpeg-turbo-devel libpng-devel giflib-devel libtiff-devel libexif-devel
    • yum install glib2-devel cairo-devel
    • git clone https://github.com/mono/libgdiplus
    • cd libgdiplus
    • ./autogen.sh
    • make
    • make install
    • cd /usr/lib64/
    • ln -s /usr/local/lib/libgdiplus.so gdiplus.dll
  • Docker
    • RUN apt-get update \

      && apt-get install -y libgdiplus

  • MacOS
    • brew install mono-libgdiplus

      After installing the Mono MDK, Copy Mono MDK Files:

      • /Library/Frameworks/Mono.framework/Versions/4.6.2/lib/libgdiplus.0.dylib
      • /Library/Frameworks/Mono.framework/Versions/4.6.2/lib/libgdiplus.0.dylib.dSYM
      • /Library/Frameworks/Mono.framework/Versions/4.6.2/lib/libgdiplus.dylib
      • /Library/Frameworks/Mono.framework/Versions/4.6.2/lib/libgdiplus.la

      And paste them to: /usr/local/lib

The original EPPlus project has been moved to Github. Please post its development related issues/pull requests at there. The main purpose of the current project is just providing an existing EPPlus for .NET Standard. There will be no further developments here.

epplus.core's People

Contributors

vahidn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

epplus.core's Issues

Error when uploading an empty excel file using SampleWebApp

Summary of the issue

It thrown an error when I created an new excel file with Office 2013 and uploaded it using SampleWebApp. I opened the excel file and filled something, then run it again, it ran well.

Environment

The in-use version: 1.5.2
Operating system: Win10 RS3
IDE: Visual Studio 2017

Example code/Steps to reproduce:

public async Task<IActionResult> FileUpload(IFormFile file)
{
	if (file == null || file.Length == 0)
	{
		return RedirectToAction("Index");
	}

	using (var memoryStream = new MemoryStream())
	{
		await file.CopyToAsync(memoryStream).ConfigureAwait(false);

		using (var package = new ExcelPackage(memoryStream))
		{
			var worksheet = package.Workbook.Worksheets[1]; // Tip: To access the first worksheet, try index 1, not 0
			return Content(readExcelPackageToString(package, worksheet));
		}
	}
}

Full Stack trace:

qq 20171128162343

Test file

test.xlsx

Get/Set Excel Rows Indexes

Hi!
Is there a way to get the row's index so we can use it as PK?
In your example you have the attribute ID, but how can you associate it with the row's index?

.Net Core on Linux

Thanks for porting EPPlus to .Net Core! Great job! But I have encountered a little
problem while testing on linux. One of it's dependencies seems to rely on on gdi32+
and so it doesn't load on linux.

System.MissingMethodException: void OfficeOpenXml.Style.ExcelColor.SetColor(System.Drawing.Color) occurred

Exception thrown while executing the following snippet of code:

workSheet.Cells[1, 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
workSheet.Cells[1, 1].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.DarkBlue);

Exception:
System.MissingMethodException: void OfficeOpenXml.Style.ExcelColor.SetColor(System.Drawing.Color) occurred

Environment: - API
Android Emulator Oreo 8.1 - API 27
Xamarin Forms: 3.1.0.697729

EPPlusCore.zip

Is Epplus going to be shutdown?

Excuse me!

I shouldn't post this question here but I don't know where it should be.

There is no update of Epplus for a very long time. Is Epplus still being maintained? Does anybody have that information?

export excel with picture in ubuntu

Summary of the issue

i have a export excel project with picture,os windows is ok ,but linux is wrong with no Unresponsive,the server cpu is increase to 99%,the picture filesize has limit?

foreach (var item in items)
{
      using (var stream = new MemoryStream(item.PicUrlByte))
      {
		var img = Image.FromStream(stream);
		ExcelPicture pic = worksheet.Drawings.AddPicture($"pic{i}", img);
		pic.SetSize(120, 120);
		var row = i - 1;
		pic.SetPosition(row, 20, 0, 10);
		worksheet.Row(i).Height = 120;
       }
}

Output:

Exception message:
Full Stack trace:

Unable to change cell background colour, EPPlus in C#

I'm trying to verify that a cell in a row is not null. If it is null, I want to change the background colour of the cell to red. After reading how to do that, I have come up with the following code:

public int verifyImportFile(FileUpload fup)
    {
        int status = 0;
        //check if there is actually a file being uploaded
        if (fup.HasFile)
        {
            //load the uploaded file into the memorystream
            using (MemoryStream stream = new MemoryStream(fup.FileBytes))
            //Lets the server know to use the excel package
            using (ExcelPackage xlPackage = new ExcelPackage(stream))
            {
                //Gets the first worksheet in the workbook
                ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];
                //Gets the row count
                var rowCnt = worksheet.Dimension.End.Row;
                //Gets the column count
                var colCnt = worksheet.Dimension.End.Column;
                //Beginning the loop for data gathering
                for (int i = 2; i < rowCnt; i++) //Starts on 2 because excel starts at 1, and line 1 is headers
                {
                    //If there is no value in column 3, proceed
                    if (worksheet.Cells[i, 3].Value == null)
                    {
                        worksheet.Cells[i, 3].Style.Fill.PatternType = ExcelFillStyle.Solid;
                        worksheet.Cells[i,3].Style.Fill.BackgroundColor.SetColor(Color.Red);
                        status = 1;
                    }                        
                }
                xlPackage.Save();
            }               
        }
        return status;
    }

What I do know from testing is that if a null value is found, it enters the if statement that checks for nulls. It seems to be running the code to change the background colour. After it loops through the entire excel sheet, the variable status does change to 1 and is displayed in a popup. From my understanding of how to do this, it is running properly but the background colour stays white.

Error When Opening Sample2 Created on Ubuntu in Windows Excel

I installed EPPlus.Core on Windows and Ubuntu. Made a few changes for compatibility so Windows and Linux source is identical.

Main
string working = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo outputDir = new DirectoryInfo(working);
Sample1&2 Used Path.Combine
string outPath = Path.Combine(outputDir.FullName, "Sample1.xlsx");
FileInfo templateFile = new FileInfo(outPath);

Works perfectly on Windows and am able to open in Excel 2010.
Runs perfectly on Ubuntu.
Move Ubuntu output to Windows. Sample1 opens up perfectly.
Sample2 gives an error and prompts me to repair it. It opens perfectly after being repaired and I don't see any issue.

The error log is:
   xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>error343960_01.xml</logFileName><summary>Errors were detected in file 'C:\temp\Sample2.xlsx'</summary><removedRecords summary="Following is a list of removed records:"><removedRecord>Removed Records: Named range from /xl/workbook.xml part (Workbook)</removedRecord></removedRecords></recoveryLog>

The named range "SubTotalName" is there and correct.

Object must implement IConvertible.

Hi
i have this error on package.SaveAs "System.InvalidCastException: 'Object must implement IConvertible.'
" with nuget package EPPlus.Core 1.52
the strange thing is that it works fine if i attached project EPPlus.Core to solution
how it is possibile?? aren't the same?

Getting the error "Unable to load DLL 'libdl'" on Ubuntu docker container with container image, microsoft/aspnetcore-build:2.0

I am trying to generate the excel sheet, using EPPlus.Core in dotnet core 2.0 framework. The generation works fine on local machine running windows. When I test the same on Ubuntu docker images, it fails with the below exception:

Unable to load DLL 'libdl': The specified module or one of its dependencies could not be found.
(Exception from HRESULT: 0x8007007E)
at Interop.Libdl.dlopen(String fileName, Int32 flag)
at System.Drawing.SafeNativeMethods.Gdip.LoadNativeLibrary()
at System.Drawing.SafeNativeMethods.Gdip..cctor()

The same used to work fine when I used the dotnet core 1.1, with libgdiplus being explicitely installed. But this setup fails with dotnet core 2.0.

The complete docker file is as below:

FROM microsoft/aspnetcore-build:2.0

RUN apt-get update
RUN apt-get install -y libgdiplus

RUN npm install typings -g

COPY . /app
WORKDIR /app/MyWeb

RUN ["dotnet", "--info"]
RUN ["dotnet", "restore"]

EXPOSE 5000/tcp
ENV ASPNETCORE_URLS http://*:5000

RUN ["dotnet", "publish"]

WORKDIR /app/MyWeb/bin/Debug/netcoreapp2.0/publish

ENTRYPOINT ["dotnet", "MyWeb.dll"]

Bound to clash ?

How on earth could this be used (as expected) in an asp.net core 2.1 web app with angular project template if the dependencies include .net framework versions 4, 4.5 and 4.6 ?

These are incompatible with .net core !! surely ?

Is it meant to be used as a project that you import to your solution and then reference the .net 4. dependencies in the *.csproj file ?

EPPlus.Core, Persian(B Fonts) Font Family Not Affected

Summary of the issue

The problem is that when I download the file and open it on Excel 2016, the font family not affected but on the font name box, it appears. If I focus on the combo box and press Enter, the font family will be affected.
How can I solve this problem ?

Environment

The in-use version:
Operating system: 
IDE: (e.g. Visual Studio 2015)

Example code/Steps to reproduce:

worksheet.Row(rowIndex).Style.Font.SetFromFont(new Font("B Nazanin", 14, FontStyle.Regular | FontStyle.Regular));

Output:

Exception message:
Full Stack trace:

[Exception] Reading file on linux

Runing a new project to read a simple file on linux:

Unhandled Exception: System.DllNotFoundException: Unable to load DLL 'ole32.dll': The specified module could not be found.
(Exception from HRESULT: 0x8007007E)
at OfficeOpenXml.Utils.CompoundDocument.StgIsStorageFile(String pwcsName)
at OfficeOpenXml.ExcelPackage.ConstructNewFile(String password)

work with a lot column

Summary of the issue

i have a file with 250 column
if i want to work with this file i must write a command for a column to read or write.
is there any way to read all of column with data and map to a class use by header or index?
thanks

ExcelPackage crash dotnet

Hi!
If you type FileInfo to new ExcelPackage with file that doesn't exist, dotnet at mac goes to hell. I tried to commit solution for this but I don't have permission.

  /// <summary>
		/// Create a new instance of the ExcelPackage class based on a existing file or creates a new file.
		/// </summary>
		/// <param name="newFile">If newFile exists, it is opened.  Otherwise it is created from scratch.</param>
public ExcelPackage(FileInfo newFile)
        {
            if(!newFile.Exists)
            {
                        throw new FileNotFoundException("The file was not found.");
            }
            Init();
            File = newFile;
            ConstructNewFile(null);
        }
        /// <summary>
        /// Create a new instance of the ExcelPackage class based on a existing file or creates a new file.
        /// </summary>
        /// <param name="newFile">If newFile exists, it is opened.  Otherwise it is created from scratch.</param>
        /// <param name="password">Password for an encrypted package</param>
        public ExcelPackage(FileInfo newFile, string password)
        {
			if (!newFile.Exists)
			{
				throw new FileNotFoundException("The file was not found.");
			}
            Init();
            File = newFile;
            ConstructNewFile(password);
        }
        /// <summary>
        /// Create a new instance of the ExcelPackage class based on a existing template.
        /// If newFile exists, it will be overwritten when the Save method is called
        /// </summary>
        /// <param name="newFile">The name of the Excel file to be created</param>
        /// <param name="template">The name of the Excel template to use as the basis of the new Excel file</param>
        public ExcelPackage(FileInfo newFile, FileInfo template)
        {
            if (!newFile.Exists || !template.Exists)
			{
				throw new FileNotFoundException("The file was not found.");
			}

            Init();
            File = newFile;
            CreateFromTemplate(template, null);
        }
        /// <summary>
        /// Create a new instance of the ExcelPackage class based on a existing template.
        /// If newFile exists, it will be overwritten when the Save method is called
        /// </summary>
        /// <param name="newFile">The name of the Excel file to be created</param>
        /// <param name="template">The name of the Excel template to use as the basis of the new Excel file</param>
        /// <param name="password">Password to decrypted the template</param>
        public ExcelPackage(FileInfo newFile, FileInfo template, string password)
        {
			if (!newFile.Exists || !template.Exists)
			{
				throw new FileNotFoundException("The file was not found.");
			}
            Init();
            File = newFile;
            CreateFromTemplate(template, password);
        }
        /// <summary>
        /// Create a new instance of the ExcelPackage class based on a existing template.
        /// </summary>
        /// <param name="template">The name of the Excel template to use as the basis of the new Excel file</param>
        /// <param name="useStream">if true use a stream. If false create a file in the temp dir with a random name</param>
        public ExcelPackage(FileInfo template, bool useStream)
        {
			if (!template.Exists)
			{
				throw new FileNotFoundException("The file was not found.");
			}
            Init();
            CreateFromTemplate(template, null);
            if (useStream == false)
            {
                File = new FileInfo(Path.GetTempPath() + Guid.NewGuid().ToString() + ".xlsx");
            }
        }
        /// <summary>
        /// Create a new instance of the ExcelPackage class based on a existing template.
        /// </summary>
        /// <param name="template">The name of the Excel template to use as the basis of the new Excel file</param>
        /// <param name="useStream">if true use a stream. If false create a file in the temp dir with a random name</param>
        /// <param name="password">Password to decrypted the template</param>
        public ExcelPackage(FileInfo template, bool useStream, string password)
        {
			if (!template.Exists)
			{
				throw new FileNotFoundException("The file was not found.");
			}
            Init();
            CreateFromTemplate(template, password);
            if (useStream == false)
            {
                File = new FileInfo(Path.GetTempPath() + Guid.NewGuid().ToString() + ".xlsx");
            }
        }

No need to define net45 and net46 frameworks.

<TargetFrameworks>net40;net45;net46;netstandard1.3</TargetFrameworks>

can be changed into

<TargetFrameworks>net40;netstandard1.3</TargetFrameworks>

Always target only the lowest framework which will work.

And is netstandard1.3 the lowest you can go?

Null reference exception on .GetAsByteArray()

I've implemented this simple use case and am getting a null reference exception on .GetAsByteArray()

using (var package = new ExcelPackage())
            {
                foreach (var contract in contracts)
                {
                    using (var worksheet = package.Workbook.Worksheets.Add(contract.Value.Name))
                    {
                        var dt = contract.Value.Activities.Select(r => new
                        {
                            r.Name,
                            r.User,
                            r.Status,
                            r.Time
                        })
                        .ToList();

                        worksheet.Cells["A1"].LoadFromCollection(dt);
                    }
                }

                var result = package.GetAsByteArray();

Edit: Exception is being thrown by CellsStoreEnumerator.Init. seems like _cellStore is possibly null?

Loading excel file with images fails on SaveAs : System.Drawing.Image.Save - Value cannot be null - Parameter name: encoder

I'm using EPPlus.Core to load in a xlsm file, insert values into the file, then save it to a stream which is sent as an email attachment.

The process fails with the following error:

An unhandled exception occurred while processing the request.
ArgumentNullException: Value cannot be null.
Parameter name: encoder
System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)

I'm assuming that EPPlus is scanning the whole file, then saving everything to the new stream, but when it encounters an image it doesn't know/like the image format (jpg/png/?) and then doesn't know what encoder to use.

I'm only inserting data into the spreadsheet before saving, which will ultimately run several complicated macros on the recipients machine, so I don't want to have to build the entire spreadsheet from scratch (which would give me the control over image encoding).

Is there somewhere that the encoding can be set globally for the new stream?

Environment

EPPlus.Core (1.5.4)
.Net Core 2.0

Example code/Steps to reproduce:

If images are stripped out the following works, otherwise fails at excel.SaveAs

public async Task Test()
        {
            string myFile = "ClientApp/src/assets/templates/test-workbook.xlsx";
            var file = Path.Combine(Directory.GetCurrentDirectory(), myFile);
            FileInfo template = new FileInfo(file);

            MemoryStream outputStream = new MemoryStream();

            using (var excel = new ExcelPackage(template))
            {

                var ws = excel.Workbook.Worksheets[1];
                ws.Cells["B10"].Value = "Test";
                excel.SaveAs(outputStream); // Fails here
                outputStream.Position = 0;                
		// ... Code for creating & emailing attachment
	}
}

Output:

ArgumentNullException: Value cannot be null.
Parameter name: encoder
System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
OfficeOpenXml.ImageConverter.ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
OfficeOpenXml.Drawing.ExcelPicture..ctor(ExcelDrawings drawings, XmlNode node)
OfficeOpenXml.Drawing.ExcelDrawing.GetDrawing(ExcelDrawings drawings, XmlNode node)
OfficeOpenXml.Drawing.ExcelDrawings.AddDrawings()
OfficeOpenXml.ExcelWorksheet.Save()
OfficeOpenXml.ExcelWorkbook.Save()
OfficeOpenXml.ExcelPackage.Save()
OfficeOpenXml.ExcelPackage.SaveAs(Stream OutputStream)

Cannot Read Worksheet Data

Hi, I was trying to Use this library for Reading data from xlsx files and storing them into database.
I faced issue that any kind of Excell file that i tried to read returned empty Count of Worksheets (Worksheet position out of range).

My code is simple Console application:

using System;
 using System.IO;
 using System.Text;
 using OfficeOpenXml;

 namespace Mb.XlsxParseConsole
 {
    class Program
    {
        static void Main(string[] args)
        {
            string sFilename = "../../Data/_test_data.xls";
            FileInfo file = new FileInfo(sFilename);

            try {
                using (ExcelPackage package = new ExcelPackage(file)) 
                {
                    StringBuilder sb = new StringBuilder();
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
                    int rowCount = worksheet.Dimension.Rows;
                    int colCount = worksheet.Dimension.Columns;
                    bool bHeaderRow = true;

                    for (int row = 1; row <= rowCount; row++) {
                        for (int col = 1; col <= colCount; col++) {
                            if (bHeaderRow) {
                                sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
                            } else {
                                sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
                            }
                        }

                        sb.Append(Environment.NewLine);
                    }

                    System.Console.Write(sb.ToString());
                }
            } catch (Exception ex) {
                System.Console.WriteLine(ex.Message);
            }


        }
    }
 }

I tried with multiple Excell files but i was unable to read any of them.
Any suggestions ?

无法加载:System.Security.Cryptography.Native.so

引入EPPlus.Core后,部署到centos7报错:DllNotFoundException: Unable to load DLL 'System.Security.Cryptography.Native': The specified module could not be found.
不引入EPPlus.Core可以在publish文件夹中找到System.Security.Cryptography.Native.so。引入就找不到了。

Does EPPLus ASP.NET Core support .Net Standard (not .Net Core) .Net framework 4.6.1

Summary of the issue

Can not open Export xlsx in ASP.NET Core 4.5.2 in browser using InMemoryReport
I using .Net Standard (not .Net Core) in .Net Framework 4.6.1

Environment

backend: ASP.NET Core EPPlus, .Net Standard (not .Net Core) in .Net Framework 4.6.1
frontend: Chrome, angularjs

The in-use version:
Operating system: 
Win7, Visual studio 2017, 

## Example code/Steps to reproduce:
1. controller same with code example: 
HomeController.InMemoryReport()
{
            byte[] reportBytes;
            using (var package = createExcelPackage())
            {
                reportBytes = package.GetAsByteArray();
            }

            return File(reportBytes, XlsxContentType, "report.xlsx");
        }

2. Got web API response in front end to open excel in browser Chrome
response.data is the controller response.                
                    let blob = new Blob([response.data], {
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    })
                    //To support IE 
                    if (navigator.appVersion.toString()
                        .indexOf('.NET') > 0)
                        window.navigator.msSaveBlob(blob, "report.xlsx");
                    //To support Chrome
                    else {
                        var a = document.createElement("a");
                        document.body.appendChild(a);
                        a.style = "display: none";
                        let url = window.URL.createObjectURL(blob);
                        a.href = url;
                        a.download = "report.xlsx";
                        a.click();
                        window.URL.revokeObjectURL(url);
                    }
                 });

## Output:
But it showed as:
"Excel cannot open the file... because the file format or file extension is not valid. Verify..corrupted and..."
I tried to change blob type to type: 'text/plain', but it does not work.

Exception message:
Full Stack trace:


Not working in .net Core 2.0

It looks like there are some conflicts with .net Core 2.0. I'm guessing that maybe recompiling this with the CoreCompat.System.Drawing.v2 replacing the CoreCompat.System.Drawing might do it, but I would not put any money on it. Right now it looks like this might be the only thing holding me up from moving a project to .net core 2.0. Just wanting to know if you have any plans of checking into this. Thanks for all the work you have done. Looking forward to hearing from you.

Bug with using .NET Standard 2.0 library with EPPlus.Core from Xamarin.Android app

With the latest version of EPPlus.Core (1.5.4) I receive the following exception:

Error Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'System.Drawing.Common, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. Perhaps it doesn't exist in the Mono for Android profile?

My use case is the following: I have .NET Standard 2.0 library which I am using from Visual Studio 2017 Xamarin projects (Android and iOS).

After I switched to earlier version 1.5.2 (without System.Drawing, I suppose) the error has gone.

I can use this earlier version by now but I want you to consider this possible problem with System.Drawing.

Thanks.

Example for downloading file

A question, not an issue.
Could you provide an example for downloading any .xlsx file? I have tried to do that by package.Load(Stream input) method

public ActionResult Index(IFormFile file)
        {
            if (file != null)
            {
                using (var package = new ExcelPackage())
                {
                    var stream = file.OpenReadStream();
                    package.Load(stream);
                    ...
                 }
             }
         }

and got the error below:

System.Runtime.InteropServices.COMException (0x8003001D): An error in the writing process. (Exception from HRESULT: 0x8003001D (STG_E_WRITEFAULT))
at OfficeOpenXml.Utils.CompoundDocument.ILockBytes.WriteAt(Int64 ulOffset, IntPtr pv, Int32 cb, UIntPtr& pcbWritten)
at OfficeOpenXml.Utils.CompoundDocument.GetLockbyte(MemoryStream stream)
at OfficeOpenXml.ExcelPackage.Load(Stream input, Stream output, String Password)
at ContactsApp.Controllers.HomeController.Index(IFormFile file) in C:\Users\aakra\Documents\Visual Studio 2017\Projects\ContactsApp\ContactsApp\Controllers\HomeController.cs:line 142
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.d__7.MoveNext()

What is the cause?

Decrypt using password error

Unable to read encrypted excel files, using DotNet Core 2 and MacOS.

Exception has occurred: CLR/System.Runtime.InteropServices.MarshalDirectiveException
An exception of type 'System.Runtime.InteropServices.MarshalDirectiveException' occurred in EPPlus.Core.dll but was not handled in user code: 'Cannot marshal 'parameter #3': Unknown error.'
at OfficeOpenXml.Utils.CompoundDocument.CreateILockBytesOnHGlobal(IntPtr hGlobal, Boolean fDeleteOnRelease, ILockBytes& ppLkbyt)
at OfficeOpenXml.Utils.CompoundDocument.Read(Byte[] doc)
at OfficeOpenXml.Encryption.EncryptedPackageHandler.DecryptPackage(FileInfo fi, ExcelEncryption encryption)
at OfficeOpenXml.ExcelPackage.ConstructNewFile(String password)
at ExcelInputHelper.ToHashtable(String excelPath, Boolean returnJustHeader, String password) in /Users/jasonfoglia/Desktop/Eligibility/Helpers/ExcelInputHelper.cs:line 16
at Eligibility.Controllers.EligibilityController.InputFields(String inputFile, String password) in /Users/jasonfoglia/Desktop/Eligibility/Controllers/EligibilityController.cs:line 32
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext()

DataTable is not compatible with ASP.NET Core 1.0

I have tried using this package in VS2015 (installed from NuGet) but with the following line of code...

DataTable dataTable = new DataTable();

I get compile error...

DataTable does not contain a constructor that takes 0 arguments

Not that i have using System.Data; imported at the top of my class. What could be the problem?

.Net Core 2.0 Not Working

[CS0012] The type 'Image' is defined in an assembly that is not referenced. You must add a reference to assembly 'CoreCompat.System.Drawing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.

My Code is:

worksheet.HeaderFooter.OddFooter.InsertPicture(new FileInfo("Images/docWatermark.png"), PictureAlignment.Right);

.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="DocumentFormat.OpenXml" Version="2.7.2" />
    <PackageReference Include="EPPlus.Core" Version="1.5.2" />
    <PackageReference Include="iTextSharp.LGPLv2.Core" Version="1.3.2" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="2.0.0-preview2-final" />
    <PackageReference Include="OpenXMLPowerTools.Core" Version="1.0.0" />
  </ItemGroup>
</Project>

Bug: LoadFromDataReader throws an invalid row number error

The LoadFromDataReader will throw an invalid row number error if you try to load an empty table without headers. If you load the empty table with headers then the load will process successfully.

The issue is located in ExcelRangeBase.cs, Line number:1839

return _worksheet.Cells[_fromRow, _fromCol, row - 1, _fromCol + fieldCount - 1];

should be changed to

return _worksheet.Cells[_fromRow, _fromCol, (row <= 1 ? 1 : row - 1), _fromCol + fieldCount - 1];

The type initializer for 'System.Drawing.GDIPlus' threw an exception

When I create simple worksheet without formatting everything works fine. But, as long as I try to add some style or format cells it throws The type initializer for 'System.Drawing.GDIPlus' threw an exception.
This is a part of exception stack
at System.Drawing.GDIPlus.GdipGetGenericFontFamilySansSerif(IntPtr& fontFamily)\n at System.Drawing.FontFamily..ctor(GenericFontFamilies genericFamily)\n at System.Drawing.FontFamily.get_GenericSansSerif()\n at System.Drawing.Font.CreateFont(String familyName, Single emSize, FontStyle style, GraphicsUnit unit, Byte charSet, Boolean isVertical)\n at System.Drawing.Font..ctor(String familyName, Single emSize, FontStyle style, GraphicsUnit unit, Byte gdiCharSet, Boolean gdiVerticalFont)\n at System.Drawing.Font..ctor(String familyName, Single emSize, FontStyle style)\n at OfficeOpenXml.ExcelRangeBase.AutoFitColumns(Double MinimumWidth, Double MaximumWidth)\n at OfficeOpenXml.ExcelRangeBase.AutoFitColumns()\n

The code I am trying to execute are worksheet.Cells[1, 1, 4, 5].AutoFitColumns(); and any other formatting.

I am using .NET Core 1.1. Mac OS Sierra.

At Save doesn't recognize format

Hi, When i want to save Excel template with EMF, doesn't recognize the type and crash the application. The format code is

ImageFormatEMF
B96B3CAC-0728-11D3-9D7B-0000F81EF32E
Indicates the Enhanced Metafile (EMF) format.

Please!!!

Calling AutoFitColumns gives Error on Linux but works fine on Windows.

Thanks for this great library on .net core.

Summary of the issue

Calling AutoFitColumns gives Error on Linux but works fine on Windows.

Z System.TypeInitializationException: The type initializer for 'System.Drawing.GDIPlus' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'gdiplus': The specified module or one of its dependencies could not be found.

Environment

Ubuntu 16.4 and windows 10

The in-use version:
Operating system: 
IDE: (e.g. Visual Studio 2015)

Example code/Steps to reproduce:

paste your core code

Output:

Exception message:
Full Stack trace:
  Connection id "0HLADVPESJ1IA", Request id "0HLADVPESJ1IA:00000004": An unhandled exception was thrown by the application.
2017-12-28T14:22:23.447145539Z System.TypeInitializationException: The type initializer for 'System.Drawing.GDIPlus' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'gdiplus': The specified module or one of its dependencies could not be found.
2017-12-28T14:22:23.447148953Z  (Exception from HRESULT: 0x8007007E)
2017-12-28T14:22:23.447151528Z    at System.Drawing.GDIPlus.GdiplusStartup(UInt64& token, GdiplusStartupInput& input, GdiplusStartupOutput& output)
2017-12-28T14:22:23.447154433Z    at System.Drawing.GDIPlus..cctor()
2017-12-28T14:22:23.447156948Z    --- End of inner exception stack trace ---
2017-12-28T14:22:23.447159412Z    at System.Drawing.GDIPlus.GdipGetGenericFontFamilySansSerif(IntPtr& fontFamily)
2017-12-28T14:22:23.447162155Z    at System.Drawing.FontFamily..ctor(GenericFontFamilies genericFamily)
2017-12-28T14:22:23.447164711Z    at System.Drawing.FontFamily.get_GenericSansSerif()
2017-12-28T14:22:23.447167249Z    at System.Drawing.Font.CreateFont(String familyName, Single emSize, FontStyle style, GraphicsUnit unit, Byte charSet, Boolean isVertical)
2017-12-28T14:22:23.447169981Z    at OfficeOpenXml.ExcelRangeBase.AutoFitColumns(Double MinimumWidth, Double MaximumWidth)

Question for ongoing development of EPPlus.Core

First, I want to express my thankfulness to Vahid Nasiri, EPPlus.Core is a great library and we have been using it in our projects since this Jan, it helped us reduce our dev efforts tremendously.

I noticed that EPPlus added support to .NET Core 2.0 since its 4.1.0 version although the commit comments stated that it's not fully tested, I guess moving to .NET Standard is a way EPPlus would go so both .NET Framework and .NET Core can use the library but I'm not the author so that's my guessing anyway.

I am curious for the ongoing roadmap of EPPlus.Core, what's the plan? Will EPPlus.Core be discontinued some day and Vahid Nasiri contributes on EPPlus project or EPPlus.Core will be a long-term but separate project.

We are planning for tech upgrade from current .NET 1.1 to 2.0, any information on the EPPlus.Core roadmap will be helpful. Thanks.

R1C1 Formula Notation References Wrong Column Number

When using R1C1 notation, EPPlus transforms the formula and references the original column number minus one. For example, if column in original formula references 3 then EPPlus references column 2. If original formula references column -2, then EPPlus references column -3.

(1) Below we can see the formula from my original excel template:
=IFERROR( INDEX(ResourceCost, MATCH([@Level]&[@[Resource Office]],ResourceCost[Level]&ResourceCost[Office],0),3), 0)

(2) EPPlus transforms the above formula as:
=IF(ISNA(VLOOKUP(B16,ResourceCost,2)), 0, VLOOKUP(B16,ResourceCost,2))

(3) We can see it is referencing 2 when it should reference 3. Manually changing to correct column via excel "fixes" the issue. EPPlus should transform (1) as follows:
=IF(ISNA(VLOOKUP(B16,ResourceCost,2)), 0, VLOOKUP(B16,ResourceCost,2))

Note: ResouceCost, Level, Resource Office are named values i.e. ranges/table/array.

Worksheet.Cells[3, 2].Value returns #value!

I am using the Worksheet and the workbook and calling the calculate() method for every sheet and for the workbook:

         foreach (var worksheet in eppWorlSheets)
                    {
                        worksheet.Calculate();
                    }
                    this.eppWorkBook.Calculate();
           

When trying to get the value of some calculated cells that contains double it returns #value! as a string
using the below code

Worksheet.Cells[3, 2].Value.ToString());

Even the Text property return #value! and the Value property without "ToString()"

Upload Excel file details to Table

Good day @VahidN By the way thank you for this helpful package. I'm currently using this package in exporting details from my table. But I'm having some difficulties on how to upload the excel details to my table. Is there a way how to get the details from excel and then upload them in the table?

I'm currently using asp.net core. I hope you have sample for that. Thank you in advance.

Save as PDF?

Hello,

Is it possible to save a xlsx file as a PDF file?
Been looking for this over weeks now for this feature in a .net core lib.
Thanks in advance.

Export xlsx in ASP.NET Core - file is corrupted

I'm trying to export XLSX file in ASP.NET Core using EPPlus.Core library.

Here's my code:

        byte[] bytes;

        MemoryStream stream = new MemoryStream();
        using (ExcelPackage package = new ExcelPackage(stream))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
            //First add the headers
            worksheet.Cells[1, 1].Value = "ID";
            worksheet.Cells[1, 2].Value = "Name";
            worksheet.Cells[1, 3].Value = "Gender";
            worksheet.Cells[1, 4].Value = "Salary (in $)";

            //Add values
            worksheet.Cells["A2"].Value = 1000;
            worksheet.Cells["B2"].Value = "Jon";
            worksheet.Cells["C2"].Value = "M";
            worksheet.Cells["D2"].Value = 5000;

            worksheet.Cells["A3"].Value = 1001;
            worksheet.Cells["B3"].Value = "Graham";
            worksheet.Cells["C3"].Value = "M";
            worksheet.Cells["D3"].Value = 10000;

            worksheet.Cells["A4"].Value = 1002;
            worksheet.Cells["B4"].Value = "Jenny";
            worksheet.Cells["C4"].Value = "F";
            worksheet.Cells["D4"].Value = 5000;
            bytes = package.GetAsByteArray();
        }

        return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "test");

It was successfully exported a file but there is an error message when I try to open a file using Microsoft Excel I'm getting an error message:

"We found a problem with some content in 'text.xslx'. Do you want to
us to try to recover as much as we can? If you trust the source of
this workbook, click Yes."

and after I click "Yes" button, I'm getting an error message:

"Excel cannot open the file "test.xslx", because the file format or
file extension is not valid. Verify that the file has not been
corrupted and that the file extension matches the format of the file.

Moreover, I tried to unzip the xslx file and I'm getting an error message: "Can not open the file as [zip] archive. Is not archive. Warnings: Headers Error".

Also, I opened a generated file using notepad++ and it starts with "PK", so it's a zip file.

When I generate an Excel file and save it to the wwwroot folder it works fine. I used a code from talkingdotnet.com/import-export-xlsx-asp-net-core

Do you have any idea how can I solve this problem?

FileNotFoundException: Could not load file or assembly 'System.Drawing.Common, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.

Summary of the issue

I had an issue similar to this dll error: #40

So followed your steps in fixing by installing EPPlus.Core (1.5.2) and created a gdiplus.dll same to this #40 (comment)

Now the error has been changed to

FileNotFoundException: Could not load file or assembly 'System.Drawing.Common, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.

Environment

The in-use version: 1.5.2
Operating system:
Development Env: Windows 10 and the package is working.
Production Env: Ubuntu 16.04 (This is where the problem appears after I published my app)
IDE: Visual Studio 2017

Example code/Steps to reproduce:

Output:

Exception message: FileNotFoundException: Could not load file or assembly 'System.Drawing.Common, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.

screen shot 2018-03-05 at 2 54 03 pm

Amend ShowDataAs function

Within the ExcelPivotTableDataField.cs the ShowDataAs function is commented out, thus, this functionality is unavailable

Runtime error: Could not load type System.StringExtensions from assembly CoreCompat.System.Drawing

Hi, I'm trying to migrate an existing DLL using EPPlus 4.1.0 to .NET Core, thus replacing the reference to EPPlus with that to this port. At compile time I have no issues, but when consuming the library from a .NET 4.6.2 (WPF) application, I get this error when trying to create an Excel file:

could not load type System.StringExtensions from assembly CoreCompat.System.Drawing

Googling around, I found this post which seems related: https://github.com/dotnet/corefx/issues/15471. It seems that there is no viable solution to the issue right now. Is this correct? Should I just wait for a later release? Thanks you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.