I have an existing project that creates an excel spreadsheet using the Microsoft.Office.Interop.Excel.WorkbookClass and I am trying to convert the workbook object to the Microsoft.Office.Tools.Excel.Workbook, but I am getting an exception thrown stating:
"Unable to cast COM object of type
'Microsoft.Office.Interop.Excel.WorkbookClass' to class type
'Microsoft.Office.Tools.Excel.Workbook'. Instances of types that
represent COM components cannot be cast to types that do not represent
COM components; however they can be cast to interfaces as long as the
underlying COM component supports QueryInterface calls for the IID of
the interface."
Microsoft.Office.Interop.Excel.Application xlApp = null;
Microsoft.Office.Tools.Excel.Workbook xlWorkbook = null;
Microsoft.Office.Interop.Excel.Sheets xlSheets = null;
Microsoft.Office.Tools.Excel.Worksheet xlNewSheet = null;
xlApp = new Interop.Application();
xlApp.Visible = true;
xlWorkbook = (Microsoft.Office.Tools.Excel.Workbook)xlApp.Workbooks.Add(Interop.XlWBATemplate.xlWBATWorksheet);
xlSheets = xlWorkbook.Sheets as Interop.Sheets;
xlNewSheet = (Microsoft.Office.Tools.Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = "SheetName1";
Is this possible if not, what other options can I take that since the excel sheet is already created using the interop class and
If possible try to avoid using the Microsoft.Office.Tools assembly which is internal to Visual Studio Tools For Office.
I've amended your code as below:
Microsoft.Office.Interop.Excel.Application xlApp = null;
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = null;
Microsoft.Office.Interop.Excel.Sheets xlSheets = null;
Microsoft.Office.Interop.Excel.Worksheet xlNewSheet = null;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = true;
xlWorkbook = xlApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
xlSheets = xlWorkbook.Sheets as Microsoft.Office.Interop.Excel.Sheets;
xlNewSheet = xlSheets.Add(xlSheets[1], System.Type.Missing, System.Type.Missing, System.Type.Missing);
xlNewSheet.Name = "SheetName1";
It looks like to "convert" an interop workbook to a vsto workbook you just do this:
In application-level projects, you can create
Microsoft.Office.Tools.Excel.Workbook objects programmatically by
using the GetVstoObject method.
Microsoft.Office.Interop.Excel.Workbook nativeWorkbook = Globals.ThisAddIn.Application.ActiveWorkbook;
if (nativeWorkbook != null)
{
Microsoft.Office.Tools.Excel.Workbook vstoWorkbook =
Globals.Factory.GetVstoObject(nativeWorkbook);
}
Related
I am trying to update the particular cell value, but getting an error. Below is the code which I tried.
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook workbook;
excel = new Microsoft.Office.Interop.Excel.Application();
workbook = excel.Workbooks.Open(#"D:\Ride\Ride Master Sheet 05 11 2020.xlsx", ReadOnly: false, Editable: true);
//Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.Worksheets.Item[1] as Microsoft.Office.Interop.Excel.Worksheet;
Microsoft.Office.Interop.Excel.Sheets sheets = excel.Worksheets;
// Select worksheets
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item("Concentric Pricing");
if (ws == null)
return;
Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)ws.get_Range("A7", "O7");
Microsoft.Office.Interop.Excel.Range row1 = worksheet.Rows[7].Cells[1, 1];
row1.Value = "";
excel.Application.ActiveWorkbook.Save();
excel.Application.Quit();
excel.Quit();
Getting error
Unable to cast COM object of type
'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type
'Microsoft.Office.Interop.Excel._Application'.
Any help on this?
I have an excel workbook that has a button, that triggers a c# application. I need to add the returned value from the app to the excel workbook but I can't figure out how to do that while the excel workbook is already open.
I've basically been grasping at straws. Every example I've found opens a read only version of the excel workbook
Microsoft.Office.Interop.Excel._Application myExcelApp;
Microsoft.Office.Interop.Excel.Workbook myExcelWorkbook = new
Microsoft.Office.Interop.Excel.Workbook();
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
xlWorkSheet = myExcelWorkbook.Sheets["Sheet1"];
xlWorkSheet = myExcelWorkbook.ActiveSheet;
myExcelApp = new Microsoft.Office.Interop.Excel.Application();
myExcelApp =
(Microsoft.Office.Interop.Excel.Application)
System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
foreach (Microsoft.Office.Interop.Excel.Workbook item in myExcelApp.Workbooks)
{
//Select the excel target 'NAME'
if (item.Name == "DatagridviewTest.xlsm")
{
myExcelWorkbook = item;
break;
}
//Select the target workbook
xlWorkSheet = myExcelWorkbook.Sheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
//Set cell value
xlWorkSheet.Cells[5, 1] = "new value";
}
I get an unhandled exception error "System runtime COM exception"
I am unable to select range using excel interop in C#. Please let me know what am I doing wrong here. I am very new to excel interop
static void Main(string[] args)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("D:\\s1.xlsx");
Excel.Range xlTestRange;
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[2];
xlTestRange = xlWorksheet.UsedRange;
xlTestRange.Select();
xlWorkbook.Save();
xlWorkbook.Close();
xlApp.UserControl = true;
xlApp.Quit();
}
The following code worked for me in LINQPad:
var xlApp = new Excel.Application();
var xlWorkbook = xlApp.Workbooks.Open(#"path-to-excel-file");
var xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets[1];
var xlTestRange = xlWorksheet.UsedRange;
xlTestRange.Select();
xlWorkbook.Save();
xlWorkbook.Close();
xlApp.Quit();
I am attempting to add a worksheet to my existing Excel instance using C#, but I get an error of
Object not set to an instance of an object
The line that throws the code is the one that begins with newSheet =
I am not sure why this is being thrown as I declare my variable newSheet and I have instantiated xlApp ---- What do I need to alter in order for this syntax to work as expected?
public static void AddNewSheet()
{
Excel.Application xlApp;
xlApp = new Excel.Application();
Excel.Worksheet Jobs, Estimates;
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\Test.xlsx";
var xlWorkBook = xlApp.Workbooks.Open(filePath);
Excel.Worksheet newSheet;
//Add a new worksheet to the workbook
newSheet = (Excel.Worksheet)xlApp.Worksheets.Add(System.Reflection.Missing.Value,
xlWorkBook.Worksheets[xlWorkBook.Worksheets.Count],
System.Reflection.Missing.Value,
System.Reflection.Missing.Value);
}
EDIT
Additional Code - to hopefully assist with adding worksheets to already created workbook.
namespace GenerateExcelWorkbookData
{
public partial class Form1 : Form
{
public static Excel.Application xlApp;
public static Excel.Workbook xlWorkBook;
public static Excel.Worksheet xlWorkSheet;
public static Excel.Worksheet newSeet;
Main()
{
//Query Excel To Get DataTable Here
//Excel Info
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
CreateSubWorksheets();
}
public static void CreateSubWorksheets()
{
string sheetNameprefix = "SS";
Excel.Worksheet sheet1;
sheet1 = xlApp.ActiveWorkbook.Worksheets.Item["Newly Added"];
Excel.Range range = sheet1.Range["A1"].CurrentRegion;
object OriginalData = range.Value;
string OriginalAddress = range.Address;
while (range.Cells[2, 1].Value != null && range.Cells[2, 1].Value != "")
{
range.AutoFilter(1, range.Cells[2, 1].Value);
newSeet = (Excel.Worksheet)xlApp.Worksheets.Add(System.Reflection.Missing.Value,
xlWorkBook.Worksheets[xlWorkBook.Worksheets.Count],
System.Reflection.Missing.Value,
System.Reflection.Missing.Value);
//Do more stuff here
}
}
}
}
Try this...
Microsoft.Office.Interop.Excel.Application Excel = null;
Microsoft.Office.Interop.Excel._Workbook oWB = null;
Microsoft.Office.Interop.Excel._Worksheet oSheet = null;
try
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
return false;
}
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.Add();
xlWorkSheet.Name = "Details";
}
I’m trying to export a datagridview to an excel. I've found a really good solution ,copy-paste solution , but this exception appears.
This is my code, the same code that the solution I've found.
void botonCP_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.Visible = true;
xlWorkBook = xlexcel.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
}
In my opinion, interop is infuriatingly irksome to use if you don't need to. Freeing up resources is a PIA and one often seems to encounter these little issues (admittedly, this could be my lack of knowledge on the subject!).
For me, I'd just use a library such as EPPlus to acheive this.
Something like this ought to serve well and would (IMO) be easier to write, manage and debug:
//Get DataGridView into a DataTable:
var bindingSource = (BindingSource)dataGridView.DataSource;
var dataView = (DataView)bindingSource.List;
var dataTable = dataView.Table;
//Create a Spreadsheet
using (ExcelPackage excelPackage = new ExcelPackage())
{
ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add("DataExport");
ws.Cells[1,1].LoadFromDataTable(dataTable, PrintHeaders:true);
//Write to an outputstream:
excelPackage.SaveAs(outputStream);
//or filesystem:
excelPackage.SaveAs(new FileInfo(#"C:\Temp\Export.xlsx"));
}
Much easier!