【问题标题】:How to add an excel ListObject to a given worksheet in C#?如何在 C# 中将 Excel ListObject 添加到给定的工作表?
【发布时间】:2014-10-17 03:05:10
【问题描述】:

我目前正在用 C# 开发一个 excel 插件,其中包含几种可供 excel 用户和程序员 (VBA) 使用的方法(表值函数)。

如何编写一个方法,将新的 ListObject(excel 表)添加到给定的 excel 工作表,并将给定的 DataTable 绑定为数据源?类似于以下内容:

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")
{
...
}

这种方法,将 Worksheet 对象作为参数发送显然不起作用。或者可以吗?

【问题讨论】:

    标签: c# .net excel excel-addins vba


    【解决方案1】:

    经过一些研究,我找到了我的问题的答案,如何在 C# 中以编程方式将 ListObject(excel 表)添加到工作表:

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

    请参阅my article 了解此代码以及其他用于 excel 和 .net 集成的相关代码。

    【讨论】:

    • 我注释掉了 HelperFunc 行(反正我认为我不需要它),但是 RowCount 和 Column Count 不能编译。
    • 像魅力一样工作!谢谢
    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 2020-02-12
    相关资源
    最近更新 更多