I have a c# code that produces a very big array that I write in an excel worksheet. Then I create another worksheet inside the same workbook with the same big array, and I sort the latter :
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApp1
{
class Program
{
static object[,] returnDummyVariant()
{
object[,] res = new object[4,3];
res[0, 0] = "Surname";
res[0, 1] = "Height";
res[0, 2] = "Age";
res[1, 0] = "Julian";
res[1, 1] = "185";
res[1, 2] = "39";
res[2, 0] = "Mark";
res[2, 1] = "173";
res[2, 2] = "63";
res[3, 0] = "Patrick";
res[3, 1] = "193";
res[3, 2] = "23";
return res;
}
private static Excel.Range WriteTopLeft(object[,] variant, Excel.Range topLeft)
{
if (variant == null) return null;
int nL = variant.GetLength(0);
int nC = variant.GetLength(1);
if (nL * nC == 0) return null;
var worksheet = topLeft.Worksheet;
var writeRange = worksheet.Range[topLeft, topLeft.Offset[nL - 1, nC - 1]];
writeRange.Value2 = variant;
return writeRange;
}
static void Main(string[] args)
{
Application excel = new Application();
string path = @"paht\to\file\Book1.xlsx";
Workbook wb = excel.Workbooks.Open(path);
var wsData = (Excel.Worksheet)wb.Worksheets.Item[1];
wsData.Name = "Data";
var variant = returnDummyVariant();
var rData = WriteTopLeft(variant, wsData.Cells[1, 1]);
int rows = rData.Rows.Count;
int columns = rData.Columns.Count;
var ws = (Excel.Worksheet)wb.Worksheets.Add();
ws.Name = "Sorted Data";
rData = WriteTopLeft(variant, ws.Cells[1, 1]);
rData.Sort(rData.Columns[2, Type.Missing], Excel.XlSortOrder.xlDescending,
Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlSortOrder.xlAscending,
Type.Missing, Excel.XlSortOrder.xlAscending,
Excel.XlYesNoGuess.xlGuess, Type.Missing, Type.Missing,
Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin,
Excel.XlSortDataOption.xlSortNormal,
Excel.XlSortDataOption.xlSortNormal,
Excel.XlSortDataOption.xlSortNormal);
wb.Save();
wb.Close();
}
}
}
The .Sort
bit triggers an exception : System.Runtime.InteropServices.COMException: 'Reference isn't valid.'
and I cannot find why.
I tried several corrections here and there without any success.