c#接口变量的动态对象
本文关键字:动态 对象 变量 接口 | 更新日期: 2023-09-27 18:05:50
我在为接口变量创建动态对象时遇到了一个问题。
下面是一个工作簿,工作表和单元格。然后我可以像这样创建
//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.
}
}
实际上你的第一步是从数据库中读取所有需要的信息。然后使用range
创建单元格我会这样写
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
}
}
}
}