I'm working on a Jeopardy application for some practice, and I'm having trouble understanding why I am getting this error. I've narrowed it down to what I believe the issue is, but for now, here's my code...
if (questionPath != "")
{
Excel.Application myapp = new Excel.Application();
Excel.Workbook wb = myapp.Workbooks.Open(questionPath);
Excel.Worksheet sheet = (Excel.Worksheet)wb.Worksheets.get_Item(1);
var cell = (Excel.Range)sheet.Cells[1, 1];
MessageBox.Show(cell.Value);
}
Basically, sets up a new Excel, pulls in the workbook, gets the first sheet, and then looks at whatever cell I tell it to look at and displays the value (like I said, just testing/playing around).
However, if the value in cell A1 is an integer, I get a "RuntimeBinderException was unhandled" error. It says that
"An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll
Additional information: The best overloaded method match for 'System.Windows.Forms.MessageBox.Show(string)' has some invalid arguments"
However if the value is a STRING, then it works fine. I've tried using Cell.ToString(), which obviously just gives the cell as a COM. I've tried using Cell.Value.ToString, which doesn't exist.... Looking at the intellisense it says that the value IS actually being read in (I used '11' as the value).
Also, I noticed that if I ran my code below, and then tried to open up the Excel to edit it, it tells me that the Excel is locked for editting by myself. I'm guessing I need to close the connection string, but I can't figure out where to do that.
Would I close myapp, or wb, or sheet? I tried a variety of _.Close()'s and other things I thought seemed obvious, but nada. Any tips on this as well?
Thanks everyone!
For anyone else reading this, 6 years later ...
I would recommend against using ToSting() if there is a possibility of null data.
Convert.ToString() handles null, while ToString() doesn't.
In the above scenario, this:
var temp = cell.Value.ToString();
Would be much safer being this:
var temp = Convert.ToString(cell.Value);
That way, it can deal with any null data, unlike ToString().
So I found out the reason it was doing that... it's pulling in an integer. Duh. I guess you can't use Cell.Value.ToString(); in the MessageBox.Show event, so here's what I ended up needing to do, and it worked perfectly.
if (questionPath != "")
{
Excel.Application myapp = new Excel.Application();
Excel.Workbook wb = myapp.Workbooks.Open(questionPath);
Excel.Worksheet sheet = (Excel.Worksheet)wb.Worksheets.get_Item(1);
var cell = (Excel.Range)sheet.Cells[1, 1];
var temp = cell.Value.ToString();
MessageBox.Show(temp);
}
Thanks for your help! I don't seem to be getting any issues with the Excel being locked to read-only, but I didn't change anything for that either... Assuming it was user error
Related
I'm using EPPLUS.dll for doing my excel works
I tried to protect the worksheet using AllowSort and AllowAutoFilter Properties but it's not working.
worksheet.Protection.AllowSort = true;
worksheet.Protection.AllowAutoFilter = true;
worksheet.Protection.SetPassword("password");
worksheet.Protection.IsProtected = true;
I tried Below Code too but i didn't get my desired result
worksheet.Column(1).Style.Locked = true;
Epplus Lock Cells By default and Locking Cells will not Fix my Problem; the only thing I need is a protected or read-only cell while sorting and Filtering Allowed
any help would be greatly appreciated.
Have you tried moving the worksheet.Protection.IsProtected = true; to be the first statement in your block of code. Perhaps this is overriding your previous statements.
https://github.com/pruiz/EPPlus/blob/master/EPPlus/ExcelSheetProtection.cs
The below has worked for me in the past, as in it will protect the worksheet, i.e. make it read only
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
worksheet.Protection.IsProtected = true;
worksheet.View.FreezePanes(2, 1); // freeze header row
worksheet.Protection.AllowSort = true;
worksheet.Cells[worksheet.Dimension.Address].AutoFilter = true;
worksheet.Protection.AllowAutoFilter = true;
I think to password protect it, it has to be against the package not the worksheet.
So use the .Save overload if saving the package.
package.Save("password");
Or if you're saving as a ByteArray then
package.GetAsByteArray("password");
The only way i Found was, using Visual Basic Code inside of that Excel Document which locked right-click and copy-paste options.
unfortunately before excel opens the documents, that asks something about dangerous scripts and offer to disable running scripts.
at last i was impossible in my case.
I have a powerpoint slide in which an embedded excel object is present, which is embedded in the following way: insert-object-create from file-browse-display as icon.
I'm trying to open this excel sheet programmatically using c#.
The problem I'm facing is that I'm receiving the error:
"Unhandled Exception: System.Runtime.InteropServices.COMException: OLEFormat (unknown member) : Invalid request. The window must be in slide or notes view.
at Microsoft.Office.Interop.PowerPoint.OLEFormat.Activate()"
I have tried changing the viewtype to slide as follows:
presentation.Application.ActiveWindow.ViewType = PowerPoint.PpViewType.ppViewSlide;
But this doesn't seem to help and I'm receiving the same error.
`
Microsoft.Office.Interop.PowerPoint.Application PowerPoint_App = new Microsoft.Office.Interop.PowerPoint.Application();
Microsoft.Office.Interop.PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;
Microsoft.Office.Interop.PowerPoint.Presentation presentation = multi_presentations.Open(#"D:\test.pptx");
foreach (var item in presentation.Slides[1].Shapes)
{
var shape = (PowerPoint.Shape)item;
if(shape.Name.Contains("Object")) {
presentation.Application.ActiveWindow.ViewType = PowerPoint.PpViewType.ppViewSlide;
presentation.Application.Activate();
presentation.Application.ActiveWindow.Activate();
shape.OLEFormat.Activate();
Microsoft.Office.Interop.Excel.Workbook wb = (Excel.Workbook)shape.OLEFormat.Object;
}
}`
This is the code which I'm using.
Could anyone please help me on this.
Thanks in advance!
It makes the job simple while working with clean presentations using Office.Interop lib. But it gets tricky when we try to access and edit OLEObjects in the presentation.
Try this!:
PowerPoint.OLEFormat ole = shape.OLEFormat;
ole.Object.Activate();
Excel.Workbook workbook = ole.Object;
this will create a workbook instance.
Note: OLEFormat.Object is dynamic type, no need of type cast the object. but yes you need handle Error when the type cast fails.
Hope this helps.
Thanks.
I have simple piece of code
public JsonResult ParseExcel(HttpPostedFileBase file)
{
var uploadedFileContent = file.InputStream;
if (POIXMLDocument.HasOOXMLHeader(uploadedFileContent))
{
//xlsx
var workbook = new XSSFWorkbook(uploadedFileContent);
var sheet = workbook.GetSheetAt(0);
}
return new JsonResult{};
}
So then I try to create a workbook using NPOI with uploaded Excel file, I get error: Exception details:
Message: The hyperlink for cell G33 references relation rId5, but that didn't exist!
I found out that this happens because G33 cell has a hyperlink, which is like this: xxx#yyy.com'. It has a single quote in the end. If I remove single quote, everything works as expected. Is there any other way to solve this problem rather that editing Excel file and removing single quote?
I tried using WorkbookFactory.Create and specifying second param as ImportOption.TextOnly. I tried creating OPCPackage object first and then passing it as a param. However, I get the same message.
As passed file to XSSFWorkbook constructor, corrupts the whole thing, I did not find any other solution then to switch to a different library.
This snippet of code is from a larger function in an MVC controller where a form with a file is posted. The inputStream comes from the uploaded file:
var excelFile = new ExcelPackage(inputStream.BaseStream);
ExcelWorksheet worksheet;
try
{
worksheet = excelFile.Workbook.Worksheets["Products"];
}
catch (Exception)
{
// Second time always works?
worksheet = excelFile.Workbook.Worksheets["Products"];
}
It always crashes when trying it at first and then it will work the second time. The exception I get is "An item with the same key has already been added.". The second attempt never fails.
Sure this is working code, but people might be tempted to poke fun at me for checking this in ;)
Version:
EPPlus.dll, v3.1.3.0
I was having this same problem today. Very frustrating! I even looked into the source code of EPPlus to see what was going on, but it didn't really help.
My problem ended up being because the spreadsheet that EPPlus was reading was an .xlsx spreadsheet created by LibreOffice Calc, not by Microsoft Excel. Even though LibreOffice was exporting in the right format, and the spreadsheet could be opened in Excel, something was missing that EPPlus was expecting. As soon as I saved the spreadsheet from Excel instead of LibreOffice, no issues.
I got the same issue with 4.5.3.2 version.
Just overcome by using the second call time.
I'm struggling with a simple problem, but I can`t figure it out.
I have an excel document, which I do some processing with (using the NetOffice API). This works fine, but I want to change the row-color after the processing, so each row within the range should have the same color after being processed.
Im getting a COMException (HRESULT: 0x800A03EC) with the following code:
foreach (Excel.Range row in rg)
{
//do the processing...
...
row.Interior.Color = XlRgbColor.rgbAliceBlue;
}
I also googled for this HRESULT and tried to solve the problem, within the
Open()-Method by setting readOnly to false and editable and corruptLoad to true. That didn`t
work. I have also tried to set the interactive property to true and saved the excel file in different formats (.xls, .xlsx) but nothing worked out.
I found that the excelfile/workbook is protected. So I tried to unprotect the ActiveWorkbook like so
app.ActiveWorkbook.Unprotect();
But this also went wrong and throws a COMException that the unprotect-property of the Workbook object can not be assigned.
I hope that someone can help me with that.
Thanks in advance,
Cordell
On Workbook open pass read only parameter to false and also pass password of excel file.
Excel.Workbook workBook = excelApplication.Workbooks.Open(sMyExcelPath,0,
False,5,123,123,True,XlPlatform.xlWindows,"\t",False,False,0,True,1,0)
You can change color of Row-Color of excel-row using below code.
Excel.Worksheet workSheet = workBook.Worksheets(1);
workSheet.Rows.Interior.Color = XlRgbColor.rgbAliceBlue;
To Set Border Try below codes:
workSheet.Rows.Borders(XlBordersIndex.xlInsideHorizontal).LineStyle = XlLineStyle.xlDouble;
workSheet.Rows.Borders(XlBordersIndex.xlInsideHorizontal).Weight = 4;
workSheet.Rows.Borders(XlBordersIndex.xlInsideHorizontal).Color = ToDouble(Color.Black);
Above code change color of all rows of excel sheet. If you want to change only used range colors then try with below code.
workSheet.UsedRange.Interior.Color = XlRgbColor.rgbAliceBlue;
To set Border Try below Codes:
workSheet.UsedRange.Borders(XlBordersIndex.xlInsideHorizontal).LineStyle = XlLineStyle.xlDouble;
workSheet.UsedRange.Borders(XlBordersIndex.xlInsideHorizontal).Weight = 4;
workSheet.UsedRange.Borders(XlBordersIndex.xlInsideHorizontal).Color = ToDouble(Color.Black);