This project is read-only.

Using a variable for sheet name

Sep 17, 2010 at 5:23 AM

In the code below,  K is a static class that holds all the "global" constants.  K.SHEET1 is a string with the name of sheet1, etc.  Each variable in a list has a member, sheet, that contains the sheet name.

 

internal static HSSFWorkbook

hssfworkbook;

 

internal static HSSFSheet

sheet1;

internal static HSSFSheet sheet2;

internal static HSSFSheet sheet3;

internal static HSSFSheet

sheet4;

internal static HSSFSheet

sheet5;

 

hssfworkbook = new HSSFWorkbook();
sheet1 = hssfworkbook.CreateSheet(K.SHEET1.Replace("'", ""));
sheet2 = hssfworkbook.CreateSheet(K.SHEET2.Replace("'", ""));
sheet3 = hssfworkbook.CreateSheet(K.SHEET3.Replace("'", ""));
sheet4 = hssfworkbook.CreateSheet(K.SHEET4.Replace("'", ""));
sheet5 = hssfworkbook.CreateSheet(K.SHEET5.Replace("'", ""));

switch (currentVar.sheet)
{
    case K.SHEET1:
        {
            HSSFCell cell = sheet1.CreateRow(currentVar.row).CreateCell(currentVar.column);
            SetValueAndFormula(cell, currentVar);
            break;
        }
    case K.SHEET2:
        {
            HSSFCell cell = sheet2.CreateRow(currentVar.row).CreateCell(currentVar.column);
            SetValueAndFormula(cell, currentVar);
            break;
        }
    case K.SHEET3:
        {
            HSSFCell cell = sheet3.CreateRow(currentVar.row).CreateCell(currentVar.column);
            SetValueAndFormula(cell, currentVar);
            break;
        }
    case K.SHEET4:
        {
            HSSFCell cell = sheet4.CreateRow(currentVar.row).CreateCell(currentVar.column);
            SetValueAndFormula(cell, currentVar);
            break;
        }
    case K.SHEET5:
        {
            HSSFCell cell = sheet5.CreateRow(currentVar.row).CreateCell(currentVar.column);
            SetValueAndFormula(cell, currentVar);
            break;
        }
}

Is there anyway to simplify the entire section of code in red down to something similar to the following:

for(n=1; n<=5; n++)
{ 
    if(currentVar.sheet) == K.SHEET(n)) 
    { 
        HSSFCell cell = sheet(n).CreateRow(currentVar.row).CreateCell(currentVar.column);
        break; 
    } 
}

 

Thank you. 

Oct 2, 2010 at 5:48 AM

change the K.Sheet to a string array. I don't think this is a issue about NPOI but c#

Oct 3, 2010 at 12:01 PM

Thank you, Tony.  I will try to rewrite the code as array.