How to add an excel ListObject to a given worksheet in C#?

若如初见. 提交于 2019-12-12 17:26:23

问题


I am currently developing an excel add-in in C# with several methods (table valued functions) that will be available to excel users and programmers (VBA).

How can I write a method which adds a new ListObject (excel table) to the given excel worksheet, and bind the given DataTable as data source? Something like the following:

using Excel = Microsoft.Office.Interop.Excel;
...
[ClassInterface(ClassInterfaceType.AutoDual)]
public class TableFunctions {
...

public Excel.ListObject CreateListObject(Excel.Worksheet ws, string TableName, DataTable dt, string CellStr = "A1")
{
...
}

This approach, sending the Worksheet object as parameter apparently doesn't work. Or could it?


回答1:


After some research I found an answer to my question, how to add a ListObject (excel table) to a worksheet programmatically in C#:

public Excel.ListObject WriteToExcelTable(Excel.Worksheet WSheet, string TableName, string CellStr = "A1", bool ClearSheetContent = false)
{
    Excel.Range range;

    if (ClearSheetContent)
        WSheet.Cells.ClearContents();  // clear sheet content

    // get upper left corner of range defined by CellStr
    range = (Excel.Range)WSheet.get_Range(CellStr).Cells[1, 1];   //

    // Write table to range
    HelperFunc.WriteTableToExcelSheet(WSheet, this._tbl, range.Address);

    // derive range for table, +1 row for table header
    range = range.get_Resize(this.RowCount + 1, this.ColumnCount);

    // add ListObject to sheet

    // ListObjects.AddEx Method 
    // http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.listobjects.addex%28v=office.14%29.aspx

    Excel.ListObject tbl = (Excel.ListObject)WSheet.ListObjects.AddEx(
        SourceType: Excel.XlListObjectSourceType.xlSrcRange,
        Source: range,
        XlListObjectHasHeaders: Excel.XlYesNoGuess.xlYes);

    // set name of excel table
    tbl.Name = TableName;

    // return excel table (ListObject)
    return (Excel.ListObject)tbl;
}

See my article about this and other related code for excel and .net integration.



来源:https://stackoverflow.com/questions/25460922/how-to-add-an-excel-listobject-to-a-given-worksheet-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!