接口变量C#的动态对象

时间:2016-09-05 05:40:27

标签: c#

我在为接口变量创建动态对象时遇到问题。

下面是一个工作簿,工作表和单元格。那么我可以像这样创建

// excelFileBo包含excel工作簿位置和工作表名称。

List<ExcelFileBo> excelFileBo ;
    IWorkbook wbi1 = workbookSet.Workbooks.Open(exFileBo.WBLocation);
    SpreadsheetGear.IWorksheet ws1 = wbi1.Worksheets[exFileBo.WBSheetName];
    SpreadsheetGear.IRange wc1 = ws1.Cells;

但是如何动态地为多个工作簿,工作表和单元格创建对象?

 foreach (ExcelFileBo exFileBo in excelFileBo)
            {
                if (System.IO.File.Exists(exFileBo.WBLocation))
                {
                     // how to create IWorkbook objects,IWorksheet object and IRange dynamically for all excel workbooks.
                }                
            }   

请帮我这样做?

1 个答案:

答案 0 :(得分:0)

实际上,您的第一步是从数据库中读取所有必需的信息。然后,您只需使用IRange

创建单元格

我会像这样写

string workSheetSQL = "Select * From [WorkSheetTable]";
using (SqlConnection cnn = new SqlConnection("connection string here"))
{
using (SqlCommand sheetCommand = new SqlCommand(workSheetSQL, cnn))
{
    using (SqlDataReader sheetReader = sheetCommand.ExecuteReader())
    {
        while (sheetReader.Read())
        {
            SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
            SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["Sheet1"];
            SpreadsheetGear.IRange cells = worksheet.Cells;

            // Set the worksheet name.
            worksheet.Name = sheetReader["WBSheetName"].ToString();
            //I assume FunctionWBId value is foreign key for cell Table, otherwise remove WHERE clause from following sql query
            string cellsSQL = "Select * From [CellsTable] where FunctionWBId = "+sheetReader["FunctionWBId"].ToString();
            // Load cell values.

            using (SqlCommand cellCommand = new SqlCommand(cellsSQL, cnn))
            {
                using (SqlDataReader cellReader = cellCommand.ExecuteReader())
                {
                    while (cellReader.Read())
                    {
                        cells[cellReader["ExcelCellNo"]ToString()].Value = cellReader["IOValue"].ToString();
                        //Add more properties to each cell if you wish in the same way
                    }
                }                   
            }
            workbook.SaveAs(sheetReader["WBLocation"].ToString()); 
            //Add more properties to workbook if you wish in the same way
        }
    }
}
}