kieky bouvier

kieky bouvier

  • NA
  • 58
  • 83.4k

Automatic Range using Excel Interop

Feb 2 2011 9:10 AM

This is my code : 

Microsoft.Office.Interop.Excel.Application();
string filePath = Server.MapPath(@"~\\Staf\\TestLucene\\" + strFileName.ToString());

Microsoft.Office.Interop.Excel.Workbook workbook = application.Workbooks.Open(filePath, Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);

int numSheet = workbook.Sheets.Count;
for (int num = 1; num < numSheet + 1; num++)
{
     Microsoft.Office.Interop.Excel.Worksheet sheet = (Worksheet)workbook.Worksheets[num];
     Range excelRange = (Range) sheet.get_Range("A1", "H10");
     object[,] valueArray = (object[,])excelRange.Value2;
     for (int i = 1; i <= valueArray.GetLength(0); i++ )
     {
          for (int j = 1; j <= valueArray.GetLength(1); j++)
          {
               string text = Convert.ToString(valueArray[i, j]);
          }
     }
}
// Close word.
workbook.Close(false);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
application.Application.Quit();

With this code, I just got the information in range A1:H10. Can I make it automatic? Like when I count of existing sheets in workbook?

int numSheet = workbook.Sheets.Count; 
it means I will always read no matter how much the existing sheet in a workbook.
cz I 'll do looping as much as number of that sheet.
Can I do this thing in range?
so that I should not determining the range A1:H10

Im sorry if its Code is messy, or if i missed to give any info. i just dont know what i should post to help you giving me an answer.

thx,


Answers (3)