How to know whether workbook contains the sheet? Poi - c#

When using Poi, even it doesn't have the sheet, it automatically creates the sheet. How to know whether it contains the sheet?
public bool Check(string Filepath, string sheetname)
{
HSSFWorkbook workbook;
using(FileStream stream = new FileStream(Filepath, FileMode.Open, FileAccess.Read){
workbook = new HSSFWorkbook(stream);
}
return workbook.contains(sheetname);

Unfortunately, NPOI / POI does not really have that feature. There is a worksheet.GetSheetAt(index) method, but it throws an exception when you try to get an index that does not exist. So if you want to try looping through possible index numbers, make sure you put a try-catch inside your loop.

Related

Is there a way to format an Aspose.Cells generated excel sheet without calling Workbook.Save()?

My customer has a use case for exporting search results to a spreadsheet. I would like to return a formatted spreadsheet to them, but the only way I can get the formatting changes to "stick" is by calling
workbook.Save(memoryStream, SaveFormat.Xlsx);
The problem with calling the method above, is that a spreadsheet will actually be saved to my local project folder, which is not desired behavior. How can I return the spreadsheet without calling workbook.Save()?
public byte[] ExportSpreadsheet(List<Result> results)
{
var workbook = MakeWorkbook(results);
var memoryStream = new MemoryStream();
workbook.Save(memoryStream, SaveFormat.Xlsx); // this saves the spreadsheet in the project
memoryStream.Seek(0, SeekOrigin.Begin);
var byteArray = memoryStream.ToArray();
return byteArray;
}
private Workbook MakeWorkbook(List<Result> results)
{
var workbook = new Workbook();
AddDataToWorkbook(workbook);
ApplyFormattingAfterData(workbook);
return workbook;
}
workbook.Save(memoryStream, SaveFormat.Xlsx);
You are doing ok. This line will save the workbook to stream and not on physical filepath. It won't save to your project's folder or path.
PS. I am working as Support developer/ Evangelist at Aspose.

Saving an ExcelPackage with exclusive lock of excel, giving error after opening excel file - C# - EPPlus

My objective is to write some data into an excel.
Here i am opening a file with file stream by exclusive lock (FileMode.Open, FileShare.Read etc., I need to lock the file to restrict others writing into excel while i am processing.) then writing some content into it and finally close the stream, so that other threads can write into this file. I am using EPPlus(5.7.4) version.
The code i am using here is :
public void WriteToExcel()
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
using (var excelPackage = new ExcelPackage(stream))
{
DoSomething(excelPackage);
excelPackage.SaveAs(stream);
stream.Close();
}
}
public void DoSomething(ExcelPackage excelPackage)
{
var cell = excelPackage.Workbook.Worksheets[0].Cells[2, 3];
cell.Value = "some value";
}
I put a break point in using statement and opened excel in the middle of execution and it showing a message saying like below which is correct.
But once i finish with execution when i try to open excel file it showing below error message.
We found a problem with some content in Sample.xlsx. Do you want us to try to recover as much as we can? if you trust the source of this book, Click Yes
I tried in different ways but none worked for me, as same error message is displaying. Can someone help me resolving this issue.
The problem is that you're reading from and rewriting to the same file stream simultaneously.
You can test this by changing excelPackage.SaveAs(new FileInfo("Book2.xlsx")); and create a new file - your file will be created without any issues.
You could open your original document, write the changes to a new file, then delete the original file and rename the new file back to the original name:
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var stream = new FileStream("Book1.xlsx", FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
using (var excelPackage = new ExcelPackage(stream))
{
DoSomething(excelPackage);
excelPackage.SaveAs(new FileInfo("Book2.xlsx"));
}
File.Delete("Book1.xlsx");
File.Move("Book2.xlsx", "Book1.xlsx");
The caveat with this is that if you have multiple things trying to access that file, then they might throw FileNotFound exceptions if they happen to try to open Book1.xlsx after it's delete and before Book2.xlsx is renamed.
That said, if you're dealing with that level of parallelism then you shouldn't be using a Excel file.
Side note: You don't need stream.Close(); as the using block automatically closes the stream.
Below code useful to me, you can refer it.
public void WriteToExcel()
{
string path = #"C:\Use**op\aa.xlsx";
FileInfo file = new FileInfo(path);
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package = new ExcelPackage(file))
{
DoSomething(package);
}
}
public void DoSomething(ExcelPackage package)
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
worksheet.Cells[2,4].Value = "some value";
package.Save();
}

NPOI - Loading an Excel file causes Wrong Local header signature: 0xE011CFD0

Has anybody an idea what may cause this error
'Wrong Local header signature: 0xE011CFD0'
var path = #"C:\Excel.xls";
using (var fs = File.OpenRead(path))
{
var wb = new XSSFWorkbook(fs);
}
Im using: https://github.com/dotnetcore/NPOI
Leaving this in case other people pass by here.
.xls is the old Excel format. With that format you should create a new HSSFWorkbook instance. The XSSFWorkbook is used with the new .xlsx format.
Both types implement the IWorkbook interface so you can build your code around this interface and determine the workbook instance's type at runtime.
I created a simple Excel component and here is the constructor:
private readonly bool _useOldExcelFormat;
private readonly IWorkbook _workbook;
public NpoiExcelManager(bool useOldExcelFormat = false)
{
_useOldExcelFormat= useOldExcelFormat;
if (_useOldExcelFormat)
{
_workbook = new HSSFWorkbook();
}
else
{
_workbook = new XSSFWorkbook();
}
}
You'll discover a few differences between HSSFWorkbook and XSSFWorkbook so sometimes you'd have to write specific code for each implementation but those cases are very rare.
I'd say around 95% of the IWorkbook interface is working for both implementations.
Ok, I found solution:
Saved that Excel file as an .xlsx but without macros or .xlsm and it worked

NPOI - After saving to file corrupts .xlsx workbook

I used this code to write to an exciting excel file. After writing the file, when I open the file manually it is corrupted. I am using NPOI binary 2.3.0.0 Please tell how to avoid excel getting corrupted.
[Authorize]
public void ExportUsers()
{
var path = Server.MapPath(#"~\Content\ExportTemplates\") + "sample.xlsx";
FileStream sw = new FileStream(path, FileMode.Open, FileAccess.Read);
IWorkbook workbook = WorkbookFactory.Create(sw);
ISheet sheet = workbook.GetSheetAt(0);
IRow row = sheet.GetRow(12);
ICell cell = row.CreateCell(row.LastCellNum);
cell.SetCellValue("test");
workbook.CreateSheet("Ripon");
sw.Close();
using (var exportData = new MemoryStream())
{
workbook.Write(exportData);
string saveAsFileName = string.Format("Export-{0:d}.xls", DateTime.Now).Replace("/", "-");
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.BinaryWrite(exportData.GetBuffer());
System.Web.HttpContext.Current.Response.End();
}
}
New file is created but corrupted. I've seen people say this is fixed in version 2.0.6, but still not working for me
There are several problems going on here.
First, you are starting with an .xlsx file but then changing the download file extension to .xls. .xls and .xlsx are not the same file format; the former is a binary format, while the latter is a zipped XML format. If you save the file with the wrong extension, then Excel will report the file as corrupted when it is opened.
Second, you are using the wrong method to get the data from the MemoryStream. GetBuffer will return the entire allocated internal buffer array, which will include any unused bytes that are beyond the end of the data if the buffer is not completely full. The extra null bytes will cause the downloaded file to be corrupted. If you want to get just the data in the buffer then you should use ToArray instead.
Third, it looks like you are using the ASP.NET MVC framework (based on the presence of the [Authorize] attribute on your method) but you are directly manipulating the current response instead of using the controller's built-in File method for returning a downloadable file. I would recommend using the built-in methods where possible, as it will make your code much cleaner.
Here is the corrected code:
[Authorize]
public ActionResult ExportUsers()
{
var path = Server.MapPath(#"~\Content\ExportTemplates\") + "sample.xlsx";
FileStream sw = new FileStream(path, FileMode.Open, FileAccess.Read);
IWorkbook workbook = WorkbookFactory.Create(sw);
ISheet sheet = workbook.GetSheetAt(0);
IRow row = sheet.GetRow(12);
ICell cell = row.CreateCell(row.LastCellNum);
cell.SetCellValue("test");
workbook.CreateSheet("Ripon");
sw.Close();
var exportData = new MemoryStream();
workbook.Write(exportData);
exportData.Seek(0, SeekOrigin.Begin); // reset stream to beginning so it can be read
string saveAsFileName = string.Format("Export-{0:d}.xlsx", DateTime.Now).Replace("/", "-");
return File(exportData, "application/vnd.ms-excel", saveAsFileName);
}

NPOI 2.2.1 generates incorrect XLSX file

I have NPOI 2.2.1 and I realized that when generating XLSX file and opening with Excel 2013, a message box telling that a problem was encountered but Excel could try to recover from it. When I click "Yes", the sheet is finally shown.
This is the code:
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet(this.Title);
using (var exportData = new MemoryStream())
{
workbook.Write(exportData);
return exportData.GetBuffer();
}
As you see, I am only creating the workbook, adding a sheet and then returning the bytes array. That array is stored in file using this code:
string targetFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), String.Concat(btnExportar.Tag, "_", DateTime.Now.ToString("yyyyMMddHHmmss"), ".xlsx"));
System.IO.File.WriteAllBytes(targetFile, xls.GetExcelData());
With XLS files there is no problem.
Regards
Jaime
The problem is not with NPOI, but with your use of GetBuffer(). That is not the method you want to use for this purpose, as GetBuffer() returns the raw buffer underlying the memory stream (usually oversized), without cutting it off at the current position of the stream. This will leave uninitialized data at the end, causing the error message in Excel.
The get all the bytes from a MemoryStream, use ToArray():
using (var exportData = new MemoryStream())
{
workbook.Write(exportData);
// return exportData.GetBuffer();
return exportData.ToArray();
}

Categories

Resources