tags:

views:

52

answers:

1

I have a Excel Workbook that I use as a report template. I change the datasource on each pivot and datatable in a C# app. When I change the datatable datasource it tweeks the columns. Is there a way to force the column order?

private void RefreshRawData(string dataSource, string connection)
{
    xl._Worksheet ws = (xl._Worksheet)xlTemplate.Worksheets["Raw Data"];
    xl.ListObject table = ws.ListObjects["Table_ExternalData_1"];
    xl.QueryTable qt = table.QueryTable;
    qt.CommandText = dataSource;
    qt.Connection = GetExcelConnectionString((string)qt.Connection);
    qt.BackgroundQuery = false;
    qt.Refresh(m);
    Marshal.ReleaseComObject(ws);
    Marshal.ReleaseComObject(table);
    Marshal.ReleaseComObject(qt);
    ws = null;
    table = null;
    qt = null;
}
+1  A: 

Welcome to the wild world of Interop.

I had to delete and recreate the table.

Please take note to the arguments in the ListObject.Add function They are odd creatures.

private void RefreshRawData(string dataSource, string connection)
{
    xl._Worksheet ws = (xl._Worksheet)xlTemplate.Worksheets["Raw Data"];
    xl.ListObject table = ws.ListObjects["Table_ExternalData_1"];
    xl.QueryTable qt = table.QueryTable;
    string connStr = GetExcelConnectionString((string)qt.Connection);
    table.Delete();
    xl.Range r = ws.get_Range("A1", "A1");
    table = ws.ListObjects.Add(xl.XlListObjectSourceType.xlSrcExternal, (object)connStr, m, xl.XlYesNoGuess.xlGuess, r);
    qt = table.QueryTable;
    qt.CommandType = xl.XlCmdType.xlCmdSql;
    qt.CommandText = dataSource;
    qt.RowNumbers = false;
    qt.FillAdjacentFormulas = false;
    qt.PreserveFormatting = true;
    qt.RefreshOnFileOpen = false;
    qt.BackgroundQuery = true;
    qt.RefreshStyle = xl.XlCellInsertionMode.xlInsertDeleteCells;
    qt.SavePassword = false;
    qt.SaveData = true;
    qt.AdjustColumnWidth = true;
    qt.RefreshPeriod = 0;
    qt.PreserveColumnInfo = true;
    qt.ListObject.DisplayName = "Table_ExternalData_1";
    qt.Refresh(false);
    Marshal.ReleaseComObject(ws);
    Marshal.ReleaseComObject(table);
    Marshal.ReleaseComObject(qt);
    ws = null;
    table = null;
    qt = null;
}
Chris