Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The SaveAsync taking a stream is failing because the Workbook.Save is… #125

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions ExcelMapper/ExcelMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1082,11 +1082,32 @@ public async Task SaveAsync<T>(Stream stream, IEnumerable<T> objects, string she
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public async Task SaveAsync<T>(Stream stream, IEnumerable<T> objects, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var ms = new MemoryStream();
public async Task SaveAsync<T>(Stream stream, IEnumerable<T> objects, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null) {
using var ms = new NpoiMemoryStream() { AllowClose = false };
Save(ms, objects, sheetIndex, xlsx, valueConverter);
await SaveAsync(stream, ms);
await SaveAsync(stream, ms);
}

/// <summary>
/// The above code fails because the Workbook.Save closes the stream
/// before it can copy the data between the streams.
/// </summary>
public class NpoiMemoryStream : MemoryStream {
public NpoiMemoryStream() {
// We always want to close streams by default to
// force the developer to make the conscious decision
// to disable it. Then, they're more apt to remember
// to re-enable it. The last thing you want is to
// enable memory leaks by default. ;-)
AllowClose = true;
}

public bool AllowClose { get; set; }

public override void Close() {
if (AllowClose)
base.Close();
}
}

/// <summary>
Expand Down