强制列顺序,Excel数据表

时间:2010-06-10 20:14:45

标签: c# excel

我有一个Excel工作簿,我将其用作报告模板。我在C#应用程序中更改每个数据透视表和数据表的数据源。当我更改数据表数据源时,它会调整列。有没有办法强制列顺序?

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 个答案:

答案 0 :(得分:1)

欢迎来到Interop的狂野世界。

我必须删除并重新创建表格。

请注意ListObject.Add函数中的参数 他们是奇怪的生物。

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;
}