sheet.Cell [,]包装类

时间:2011-06-22 05:42:40

标签: c# .net excel vsto wrapper

我正在尝试为:

创建一个包装器C#类
sheet.Cells[int row, int colmn].Value = "some value";

任何建议还是应该找出其他方法?

提前谢谢。

注释:
澄清, 工作表是Excel工作表。我们有第三方组件来编写excel报告。现在我们需要更新报告,因为此第三方组件已更新。我需要做的是创建一个模仿

的类
sheet.Cell[int row, int colmn].Value = “Some Value”;  

我正在寻找本文所述的内容:
http://pietschsoft.com/post/2007/03/17/C-Give-your-object-a-Default-Indexer-Property.aspx

但是,当索引器有两个参数时,它会变得复杂。

这是我提出的解决方案。这可能不是最好的解决方案。但是,我找不到别的办法。

public class SheetClass  
{  
    public SheetWrapper Cells;

    public SheetClass(Worksheet _sheet)
    {
      Cells = new SheetWrapper(_sheet);
    }
}

public class SheetWrapper 
{
    private readonly Worksheet sheet;

    public PFCell this[int x, int y]
    {
        get { return new PFCell(this.sheet, x-1, y-1); }
    }

    public SheetWrapper(Worksheet sheet) 
    {
        this.sheet = sheet; 
    }
}

public class PFCell
{
    Worksheet ws;
    int x;
    int y;

    public PFCell(Worksheet ws, int x, int y)
    {
        this.ws = ws;
        this.x = x;
        this.y = y;
    }

    public object Value
    {
      get { return ws.Cells[x,y].Value; }
      set { ws.Cells[x,y].Value = value; }
    }
}

然后在页面上我可以执行以下操作:

SheetClass sc = new SheetClass(sheet);
sc.Cells[1, 1].Value = "test";

如果有更好的方法可以做到这一点,请告诉我。

2 个答案:

答案 0 :(得分:1)

class SheetWrapper
{
    private readonly Sheet sheet;

    public SheetWrapper(Sheet sheet) { this.sheet = sheet; }

    public object this[int row, int column]
    {
        get { return sheet.Cells[row, column].Value; } // add null checks, etc
        set { sheet.Cells[row, column].Value = value; }
    }
}

答案 1 :(得分:1)

似乎您试图保持与标准Excel互操作代码完全相同的语法,但使单元格索引从2开始而不是从1开始。我对Excel对象模型了解不多,但看起来这应该可行:

public class SheetClass  
{
    RangeWrapper cells;
    public RangeWrapper Cells { get; }

    public SheetClass(Worksheet _sheet)
    {
        cells = new RangeWrapper(_sheet.Cells);
    }
}

public class RangeWrapper 
{
    private readonly Range cells;

    public Cell this[int x, int y]
    {
        get { return Cells[x-1, y-1]; }
    }

    public RangeWrapper(Range cells)
    {
        this.cells = cells;
    }
}
相关问题