I have the following method that opens a Excel workbook and returns it to be used in another method.
private Excel.Workbook openWorkbook()
{
// Get excel file path returns the file path of the excel workbook if it exists, otherwise returns null.
List<string> filePaths = getExcelFilePath();
if (filePaths != null)
{
return excel.Workbooks.Open(filePaths[0]);
}
return null;
}
As you can see, I'm returning null
to avoid a try-catch
for a non-exixtent workbook when I call this from another method. Is it bad practice to do this. I do a similar thing in the following method which is supposed to return a list:
private List<string> getSOsToDelete()
{
// rawData is private variable in the class. If the workbook was not open this worksheet is set to null in another method similar to openWorkbook() above.
if (rawData != null)
{
List<string> ToDeleteSOs = new List<string>();
for (int i = rawData.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row; i > 1; i--)
{
if (rawData.Cells[i, 7].Value2.ToString() != "B2B" || rawData.Cells[i, 7].Value2.ToString() != "" || rawData.Cells[i, 8].Value2.ToString() != "Trns-Inc" || rawData.Cells[i, 8].Value2.ToString() != "")
{
string SONumber = rawData.Cells[i, 3].Value2.ToString();
ToDeleteSOs.Add(SONumber);
}
}
return ToDeleteSOs;
}
return null;
}
If not so, what is the best way to write methods like these? For part 2 I guess I could return an empty list and check for length. I'm not sure which is better. However, for first method, I'm really not sure what to return if the file doesn't exist.