I have a dataobject array object[,] coming from an SQL database table loaded through SqlDataAdapter and it contains Excel formulas.
I want to paste the object into a certain range in an already opened Excel file.
I should add that everything works fine when the datatable holds strings like "this is a test" and not Excel formulas like "=SUM(A1:A5)"
But I keep running into exceptions that make no sense to me. Please advice!
Here's what I've got. What am I overlooking?
private void InsertBridgeCalcBlock()
{
Excel.Application xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
try
{
xlActiveCell = xlApp.ActiveCell;
DataTable dt = new DataTable();
try
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM " + sDBBridgeCalcTable, conn))
{
da.Fill(dt);
}
}
catch (Exception ex)
{
MessageBox.Show("Error Message:" + Environment.NewLine + ex);
}
object[,] BridgeCalcTable = new object[dt.Rows.Count + 1,dt.Columns.Count];
for (var i = 0; i < dt.Rows.Count; i++)
for (var j = 1; j < dt.Columns.Count; j++)
{
BridgeCalcTable[i, j-1] = dt.Rows[i][j];
}
Excel.Range insertBridgeCalcTableRange = xlApp.Range[xlApp.ActiveSheet.Cells[xlActiveCell.Row-2, 11], xlApp.ActiveSheet.Cells[xlActiveCell.Row-2 + dt.Rows.Count - 1, 11 + dt.Columns.Count]]; // set insertrange
xlApp.ActiveSheet.EnableCalculation = true;
insertBridgeCalcTableRange.Value = BridgeCalcTable; // fill range with data
}
catch (Exception ex)
{
MessageBox.Show("Error Message:" + Environment.NewLine + ex);
}
}
The exception reads:
System.Runtime.InteropServices.COMException (0x800A03EC):
Exception from HRESULT: 0x800A03EC at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWarpperTypes, MessageData& msgData)
at Microsoft.Office.Interop.Excel.Rage.ser_Value(obejct value) at LookApp2016.Form1.InsertBridgeCalcBlock() in ~~myfilelocation~~ line 2886