我有一个用于导入 excel 文件的服务,实现如下所示:
[Attributes.ImportFileExtension(Extension=".xls")]
[Attributes.ImportFileExtension(Extension=".xlt")]
[Attributes.ImportFileExtension(Extension=".xlsx")]
public class ExcelImportService:FileImportServiceBase,IFileImportService
{
public DataSet Import(System.IO.Stream fileStream)
{
IExcelDataReader excelReader = null;
switch (Extension)
{
case ".xls":
case ".xlt":
excelReader = ExcelReaderFactory.CreateBinaryReader(fileStream);
break;
case ".xlsx":
excelReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
break;
}
excelReader.IsFirstRowAsColumnNames = true;
DataSet dataSet = excelReader.AsDataSet();
return dataSet;
}
}
此外,我有以下代码通过正在创建的工厂调用此服务。调用该服务的代码如下所示:
try
{
var extension = Path.GetExtension(dialog.FileName);
var importService = FileImportServiceFactory.Create(extension);
var stream = dialog.OpenFile();
var data = importService.Import(stream);
stream.Close();
stream.Dispose();
var result = new FileImportedMessage { Data = data };
result.Dispatch();
}
catch (Exception e)
{
MessageDispatcher.Dispatch(new ExceptionMessage(e));
}
除非文件在导入时打开,否则导入工作会找到。
我有两个问题:
1)处理这种情况的最佳实践/策略是什么?
2)我该怎么做,或者我应该如何处理?