i've got this very strange error while trying to get the worksheets (just worksheet names) from excel (xlsx) file with EPPlus.
using (var ep = new ExcelPackage(new FileInfo(filePath)) {
foreach (var ws in ep.Workbook.Worksheets)
....
}
This works flawlesly (why shouldn't it right), but from time to time i find excel file that just throws System.NullReferenceException while trying to get worksheets.
Exception thrown: 'System.NullReferenceException' in EPPlus.dll
The thing that baffles me the most is that when i debug this and go step by step everything works fine.
This is the StackTrace:
at OfficeOpenXml.ExcelRangeBase..ctor(ExcelWorksheet xlWorksheet, String address)
at OfficeOpenXml.ExcelNamedRangeCollection.Add(String Name, ExcelRangeBase Range)
at OfficeOpenXml.ExcelWorkbook.GetDefinedNames()
at OfficeOpenXml.ExcelPackage.get_Workbook()
at isef.winformapp.Helpers.ExcelUtilities.GetWorksheets(String filePath) ...
Im just wondering whether someone has encountered a similar error
You can download and try one of those 'not working' xlsx files here if you want to try it yourself.
It's an empty xlsx file with two empty worksheets.
The error occurs because there are defined names in the workbook that refer to a sheet/table/range that no longer exists. Referenced from here
First I was able to duplicate your error. Second, I deleted these Names and your code worked fine.
Unfortunately, the exception happens anytime you reference the workbook so I see no clear way to solve this outside the package.
var wb = ep.Workbook; //also throws error when wb has invalid names
Related
I am having issue reading in some worksheet from a workbook using C# and EPPlus.
Error Message
name contains invalid characters
Even after multiple checks on the worksheet name, file name and column headers within the workbook to make sure there is no invalid characters, I am still facing the same error.
However, when I move the worksheet that i need from that same workbook to a new Excel file and save it with the same file name and worksheet name, I have no error while reading in.
Does anybody know how to solve or even encounter this problem?
Code
using (ExcelPackage xlPackage = new ExcelPackage(mStream))
{
//WorksheetId = 5
var ws = xlPackage.Workbook.Worksheets[WorksheetId]; //This is the part that is causing error
for (int i = 1; i <= ws.Dimension.End.Column; i++)
{
dt2.Columns.Add((i - 1).ToString());
}
}
Came across this LINK and realized this is actually a bug in EPPlus for version 4.5.2.2 onward.
After reverting back to the older version, everything works fine.
There is a change the "name" as mentioned in the error is not the sheet name.. There is a section in the Formular tab of the Excel software called "Name Manager".
There you will find list of names and references there. The error above per the source code of EPPlus is generated when EPPlus tries to validate the name range.
I had to modify the EPPlus source code to ignore the error since the file i was dealing with was locked and needed to be preserved as it was.
I am creating an excel with drop down values using Open XML (DocumentFormat.OpenXML). There are no errors in the code and excel gets created. But I get couple of errors while opening the excel. Excel gets opened with data correctly if I click OK to the errors and go ahead. It looks like the problem is due to the addition of namespace in order to have the dropdown values.
Question is, Is there any way to get rid of the error?
Error 1:
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
workbook, click Yes.
Error 2:
Errors were detected in file 'Sample.xlsx'
Repaired Records: Cell information
from /xl/worksheets/sheet2.xml part
Repaired Records: Cell information from
/xl/worksheets/sheet3.xml part
C# Namespace addition for creating excel:
worksheet1 = new Worksheet() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x14ac" } };
worksheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
I have a C# application which purpose is to store a big amount of data. I am using Microsoft.Office.Interop.Excel (Microsoft.Office.Interop.Excel.dll Version 14.0.0.0) to help me accomplish this. I have Excel 2007 installed.
I use the following lines:
excelApp = new Microsoft.Office.Interop.Excel.Application();
excelWorkBook = excelApp.Workbooks.Add(misValue);//*--------> LINE NOT WORKING */
excelWorksheetBeingWritten = (Excel.Worksheet)excelWorkBook.Worksheets.get_Item(1);
My code then iterates through a big list of objects, and each time a row must be written I do something like:
var startCell = excelWorksheetBeingWritten.Cells[excelLineCounter, 1];
var endCell = excelWorksheetBeingWritten.Cells[excelLineCounter, 2];
string[] tmpArray = new string[2] { stringVar1, stringVar2 };
tmpRange = excelWorksheetBeingWritten.Range[startCell, endCell];
tmpRange.Value = tmpArray;
When excelLineCounter exceeds 65536, the "HRESULT: 0x800A03EC exception" is thrown. I am perfectly aware of the (in)famous pre-Excel2007 row limit (which is precisely 65536). What I don't understand is why the interops are using that limit, when Excel 2007 (my version) has a documented limit of 1.048.576 rows.
On the other hand, if I replace the above "LINE NOT WORKING" by the following, it seems to use the Excel 2007 row limit, and the exception vanishes:
excelWorkBook = excelApp.Workbooks.Open(#"H:\Workbook1.xlsx");//*--------> LINE WORKING */
Note: "Workbook1.xlsx" is an empty workbook previously saved as "Excel Workbook (*.xlsx)"
Can someone please tell me what kind of sorcery do I need to do in order to configure the Excel Interop objects to use the Excel 2007 limits by default, preferably without having a previously saved empty .xlsx file laying around?
I encountered a similar issue yesterday and the solution is to change your Excel settings to create xlsx files by default.
In Excel: File -> Options -> Save -> Save files in this format
Your default is probably 'Excel 97-2003 (*.xls)' like mine was. If you change it to 'Excel Workbook (*.xlsx)', your code will work.
We have a VSTO addin for Excel. The main functionality creates reports that are used to generate workbooks. When I run a batch of reports, I get a System.AccessViolationException when using Excel.Worksheet.Copy, which also crashes Excel. Here's how I recreate it:
1) Open and run report #1 with a single parameter which creates one workbook. We close the workbook.
2) Open and run the same report with several parameters. This create 5 workbooks but crashes when creating the second, but ONLY if we have run the first single output report (see step 1). If we remove the report from step 1 from the batch, this creates all 5 workbooks without error.
I've checked to make sure that the sheet we are copying is from the workbook is open, and is not referencing the first report. In fact, we close the first one so I know that it's not. Again, this ONLY happens if we have the report in step one, which it does not access at all, so how could that be affecting a sheet from a completely different workbook?
This doesn't even finish out my try/catch so that I can get more info. It simply blows up Excel and I have to restart.
UPDATE:
Here's the basic code:
function void ReplaceSheets(Dictionary<Excel.Worksheet, IReportSheet> sheetReports)
{
List<string> oldNames = new List<string>(sheetReports.Count);
foreach (Excel.Worksheet oldSheet in sheetReports.Keys)
{
Excel.Worksheet veryHiddenSheet = null;
Excel.Worksheet newSheet = null;
try
{
string sheetName = oldSheet.Name;
veryHiddenSheet = WorkbookHelper.FindSheet(this.DocumentView, MakeHiddenSheetName(sheetName, "--VH--"));
veryHiddenSheet.Visible = Excel.XlSheetVisibility.xlSheetVisible; //Sheet has to be visible to get the copy to work correctly.
veryHiddenSheet.Copy(this.DocumentView.Sheets[1], Type.Missing);//This is where it crashes
newSheet = (Excel.Worksheet)this.DocumentView.Sheets[1]; //Get Copied sheet
/* do other stuff here*/
}
finally
{
veryHiddenSheet = null;
newSheet = null;
}
}
}
I never found a way in VSTO to "fix" this. I switched code to NetOffice, and I was able to get some better error message. Excel/Com was not releasing the memory attached to the spreadsheets. I rebuilt the reports from blank 2010 spreadsheets and it took care of it. I think it was a corrupted 2007 spreadsheet that may have occured on converting to 2010 or something like that. I recommend NetOffice over VSTO because the exception handling is far superior, and you have access to the source code, but it does have it's quirks. (You'll need to pay attention to loading order for taskpanes.)
Im just starting to use EPPLus Lib to create "complex" workbooks via C#, and i just ran into some trouble while trying to create two pivot tables.
The first one creates fine, but when i try to create the second one it doesnt throw any exceptions but when i try to open the worknook using excel it says
"Excel found unreadable content in 'myworkbook.xlsx'. Do you want to
recover the contents of this workbook? If you trust the source of this
workbook, clickYes"
And when i press 'yes':
Repair log ->
Removed Feature: PivotTable report from /xl/pivotTables/pivotTable2.xml part (PivotTable > view) Removed
Records: Workbook properties from /xl/workbook.xml part (Workbook)
Repaired Records: Workbook properties from /xl/workbook.xml part
(Workbook)
Here's the code that i build:
CreatePivotTable("Pivot1", "Pivot1", rng1);
CreatePivotTable("Pivot2", "Pivot2", rng2);
public void CreatePivotTable(string pivotSheet, string pivotName, ExcelRangeBase srcRange)
{
if (m_wb.Worksheets[pivotSheet] != null)
m_wb.Worksheets.Delete(pivotSheet);
var ws = m_wb.Worksheets.Add(pivotSheet);
var pivot = ws.PivotTables.Add(ws.Cells["A1"], srcRange, pivotName);
}
Any ideas?
Thanks!
What was wrong and i didnt put it in my question was that i was reopening the workbook on step before, like this:
CreatePivotTable("Pivot1", "Pivot1", rng1);
Save();
CreatePivotTable("Pivot2", "Pivot2", rng2);
private void Save()
{
m_writer.Save();
m_writer.OpenWorkbook ();
}
And since the save method of epplus closes the workbook, the program lost some sort of reference or just got lost with some info.
In short, to use epplus correctly, you should write everything u need before saving and closing the workbook, its not good to reopen.
Thank you.