Cannot insert object AddOLEObject Excel C# - c#

I am trying to add pdf file in Excel using shapes object. But every time I am getting following exception:
Cannot insert object.
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at Microsoft.Office.Interop.Excel.Shapes.AddOLEObject(Object ClassType, Object Filename, Object Link, Object DisplayAsIcon, Object IconFileName, Object IconIndex, Object IconLabel, Object Left, Object Top, Object Width, Object Height)
at WordSample.Form1.button1_Click(Object sender, EventArgs e) in C:\Test Projects\WordSample\WordSample\Form1.cs:line 30
Code:
private void button1_Click(object sender, EventArgs e)
{
try
{
Excel.Application app = new Excel.Application();
Excel.Workbook wb = null;
wb = app.Workbooks.Open(#"C:\Temp_Statoil\mal_malingsprogram.xls",
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
InsertStaticIndexSheetsPreWpkTemplate(wb);
Excel._Worksheet wsMal = (Excel._Worksheet)wb.Sheets[pageTemplate];
Excel._Worksheet wsTotalOverView = (Excel._Worksheet)wb.Sheets[pageTotal];
//foreach (Excel.Worksheet ws in wb.Worksheets)
// sheetNames.Add(ws.Name);
wsMal.Copy(wsMal, Type.Missing);
Excel._Worksheet wsCurrent = (Excel._Worksheet)wb.Sheets[(wsMal.Index - 1)];
Excel.Range unitIcon = wsCurrent.get_Range("K11", Type.Missing);
Excel.Shape shape = wsCurrent.Shapes.AddOLEObject(
Type.Missing,
#"C:\Temp_Statoil\tmpFiles\1C9.pdf",
false,
true,
#"C:\Temp_Statoil\pdf.ico",
0,
"Doubleclick to open drawing for 1C9",
unitIcon.Left,
unitIcon.Top,
Type.Missing,
Type.Missing);
shape.Locked = false;
shape.Name = "Unit drawing [1C9]";
Marshal.ReleaseComObject(shape);
((Excel._Worksheet)wb.Sheets[1]).Activate();
wb.SaveAs(
Filename: #"C:\temp\test"+DateTime.Now,
FileFormat: Excel.XlFileFormat.xlOpenXMLWorkbook,
Password: Type.Missing,
WriteResPassword: Type.Missing,
ReadOnlyRecommended: Type.Missing,
CreateBackup: Type.Missing,
AccessMode: Excel.XlSaveAsAccessMode.xlNoChange,
ConflictResolution: Type.Missing,
TextCodepage: Type.Missing,
Local: Type.Missing);
wb.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
protected void InsertStaticIndexSheetsPreWpkTemplate(Excel.Workbook wb)
{
//Insert static sheets in "Innhold-arket" (english: Index sheet).
foreach (Excel.Worksheet ws in wb.Sheets)
if (ws.Name.ToLower() != pageTemplate.ToLower())
InsertIndex(wb, ws.Name, "", "", "", ws.Name);
else
break;
}
public void InsertIndex(Excel.Workbook wb, string sheetName, string lv1, string lv2, string lv3, string linkDescription)
{
Excel.Worksheet indexSheet = (Excel.Worksheet)wb.Sheets[pageContents];
indexSheet.get_Range(string.Format("A{0}", nextIndexNo + firstIndexLine), Type.Missing).Value = nextIndexNo;
indexSheet.get_Range(string.Format("B{0}", nextIndexNo + firstIndexLine), Type.Missing).Value = lv1;
indexSheet.get_Range(string.Format("C{0}", nextIndexNo + firstIndexLine), Type.Missing).Value = lv2;
indexSheet.get_Range(string.Format("D{0}", nextIndexNo + firstIndexLine), Type.Missing).Value = lv3;
Excel.Range linkRange = indexSheet.get_Range(string.Format("E{0}", nextIndexNo + firstIndexLine), Type.Missing);
linkRange.Hyperlinks.Add(linkRange, "", string.Format("'{0}'!A1", sheetName), Type.Missing, linkDescription);
nextIndexNo++;
}
Directory structure:
Could you please help me to solve this issue.

Related

Searching multiple sheets in an excel C#

The code here grabs a name in my listbox(employeebox) and deletes the entire row on that sheet. This works and there are no errors.. My problem is that I have 19 different sheets that need to be checked, but I can only check 1 at a time with this code.. "Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[2];".. Is there any way that I can check all the sheets once the Delete button is clicked? I greatly appreciate anyone's help.
private void delete_Click(object sender, EventArgs e)
{
//create excel
Excel.Application xlexcel = new Excel.Application();
Excel.Workbook xlWorkBook = xlexcel.Workbooks.Open(#"C:\\SAMPLE.xlsx");
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[2];
//search within excel
Excel.Range usedRanage = xlWorkSheet.UsedRange;
foreach (Excel.Range row in usedRanage)
{
//grab name once selected in box
if (employeeBox.SelectedItem.Equals(row.Value))
{
row.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
MessageBox.Show("Employee Deleted.");
}
}
xlexcel.DisplayAlerts = false;
xlWorkBook.SaveAs("C:\\SAMPLE.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing,
Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close();
xlexcel.Quit();
releaseObject(xlexcel);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);
}
private void delete_Click(object sender, EventArgs e)
{
//create excel
Excel.Application xlexcel = new Excel.Application();
Excel.Workbook xlWorkBook = xlexcel.Workbooks.Open(#"C:\\SAMPLE.xlsx");
int[] Cols = { 1 };
Excel.Range curRange;
foreach (Excel.Worksheet sheet in xlWorkBook.Worksheets)
{
foreach (Excel.Range row in sheet.UsedRange.Rows)
{
foreach (int c in Cols)
{
curRange = (Excel.Range)row.Cells[1, 1];
if (curRange.Cells.Value != null)
{
if (employeeBox.SelectedItem.Equals(sheet.Cells[row.Row, c].Value.ToString()))
{
row.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
MessageBox.Show("Employee Deleted.");
}
}
}
}
}
xlexcel.DisplayAlerts = false;
xlWorkBook.SaveAs("C:\\SAMPLE.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing,
Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close();
xlexcel.Quit();
releaseObject(xlexcel);
releaseObject(xlWorkBook);
}

excel file values are not updating

In my application i have an excel sheet with button. Using C# code i'm calling the button of excel file and the excel file click event also working very fine. I placed msg box in macros in that way i verified the click event of the excel sheet button working fine.But after running the macro the values are not updating in excel sheet. Please refer my code below ,
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
xlWorkBook = xlApp.Workbooks.Open("D:test.xlsm", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet xlWorkSheet;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlApp.Run("Module1.solver", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close(false, Type.Missing, Type.Missing);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
throw (ex);
obj = null;
}
finally
{
GC.Collect();
}
}
Am I missing some function to update excel file ? And the macros I'm using are
SolverOk SetCell:="$A$6", MaxMinVal:=2, ValueOf:=0, ByChange:="$A$4:$A$6", _
apple:=1, applecurry:="GRG Nonlinear"
MsgBox "$3"
SolverOk SetCell:="$A$6", MaxMinVal:=2, ValueOf:=0, ByChange:="$A$4:$A$6", _
apple:=1, applecurry:="GRG Nonlinear"
MsgBox "$4"
SolverSolve
When you start Excel via automation, any add-ins or items in the xlstart folder are not loaded.
If your code relies on add-ins being loaded, then you will need to load them via your code.
See: https://support.microsoft.com/en-us/kb/213489

Exporting to excel with carriage returns

I am trying to export to excel from my Datagrid. The Datagrid has a column where we put comments in. In that column the comments are put on separate lines. When it exports to excel it exports in multiple rows.
Here is how it looks in my DataGrid:
Here is how it looks when I export to Excel:
Here is the code that I am using to do it:
public static void CreateExcelFromClipboard(string worksheetName, string fullFilePath, bool toOpen)
{
//Excel Application class
_Application app = new Microsoft.Office.Interop.Excel.Application();
//Get process id
int excelProcessId = GetApplicationProcessId(app);
try
{
//Add workbook
Workbook theWorkbook = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
//Add worksheet
var theWorksheet =
(Worksheet)theWorkbook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
theWorksheet.Name = worksheetName;
app.SheetsInNewWorkbook = 1;
app.DisplayAlerts = false;
theWorksheet.Activate();
//Paste to the worksheet from clpboard
theWorksheet.Paste(Type.Missing, Type.Missing);
//Apply Borders
ApplyBorder(theWorksheet.UsedRange);
//Auto Fit All columns
Range xlRange = theWorksheet.UsedRange;
// put all hardcodes in a constant class
xlRange.Font.Name = "Arial";
xlRange.Font.Size = 9;
var firstRowRange = (Range)xlRange.Rows[1, Missing.Value];
firstRowRange.EntireRow.Font.Bold = true;
firstRowRange.EntireRow.HorizontalAlignment = XlHAlign.xlHAlignCenter;
//Set Wrap Test to false
xlRange.WrapText = true;
xlRange.Columns.AutoFit();
theWorksheet.Activate();
//Save the file
theWorkbook.SaveAs(fullFilePath, XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
if (!toOpen)
{
//Clean up
app.Quit();
Marshal.ReleaseComObject(app);
}
}
catch
{
ForceExcelClose(excelProcessId);
throw;
}
finally
{
app.Visible = toOpen;
}
}

excel file to save value in cell range

protected void Page_Load(object sender, EventArgs e)
{
try
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(#"D:\Tesco\NGC\Output\temp_02Feb2012.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Worksheet sheet = (Worksheet)wb.Sheets["ExpiredAccount"];
Range excelRange = sheet.UsedRange;
Range rng1 = sheet.get_Range("A2", "A2");
rng1.Value2 = "India";
Range rng2 = sheet.get_Range("A3", "A3");
rng2.Value2 = "Good work";
// string A4D4 = GetRange("A" + 2 + ":A" + 2 + "", sheet);
}
catch (Exception ex)
{
throw ex;
}
}
i am trying to open an excel file and an particular sheet called[ExpiredAccount].where i need to set an value in that particular range
here is my code but its not saving the value only, its not throwing any error.
please let me know where i am going wrong it would great if you can help me on this
Thanks
Prince
you have to save the workbook. and release the runtime callable wrapper.
simply add this code:
wb.Close(true, Type.Missing, Type.Missing); //closes and saves the workbook
app.Quit();
Marshal.FinalReleaseComObject(app); //release the wrapper
p.s. if you weren't releasing the object, I suggest to run the Task manager, check the processes tab, and end all Excel.exe processes... there ought to be a lot of them :)

Open excel workbook but set calculations to manual

I have tried a few options but none seem to work, and some send errors.
Please let me know what I am doing wrong
public string Main(String wbPath, String wbName)
{
string cName = "";
Excel.Application xlApp;
Excel.Workbook xlWB;
Excel.Worksheet xlWS;
xlApp = new Excel.Application();
xlApp.DisplayAlerts = false;
xlApp.Calculation = Excel.XlCalculation.xlCalculationManual; //Error occurs here
xlWB = xlApp.Workbooks.Open(wbPath + wbName);
xlWB.SaveAs("vFile.html", Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml);
cName = xlWB.FullName;
xlWB.Close();
xlApp.Quit();
return cName;
}
Error code:
{"Exception from HRESULT: 0x800A03EC"}
You must open the workbook before setting the xlApp.Calculation:
static void Main(string[] args)
{
string cName = "";
var xlApp = new Application();
var xlWB = xlApp.Workbooks.Open("youpathgoeshere", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlApp.Calculation = XlCalculation.xlCalculationManual;
var xlWS = new Worksheet();
xlWB.SaveAs("vFile.html", Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml);
cName = xlWB.FullName;
xlWB.Close();
xlApp.Quit();
}
You can try this solution:
This example causes Microsoft Excel to calculate workbooks before they are saved to disk.
Excel.Application xlApp;
xlApp = new Excel.Application();
Application.Calculation = xlCalculationManual
Application.CalculateBeforeSave = True

Categories