2012-03-12 5 views
1

C#의 Excel 스프레드 시트에서 읽는 데 문제가 있습니다. 은 내가Excel 파일에서 데이터 읽기

System.Array myvalues; string[] strArray; 
Microsoft.Office.Interop.Excel.Range range = 
    worksheet.get_Range("A" + i.ToString(), "W" + i.ToString()); 

while(range.Count!=0) 
{ 
    i++; 
    //Console.WriteLine(i); 
    range = worksheet.get_Range("A" + i.ToString(), "W" + i.ToString()); 
    myvalues = (System.Array)range.Cells.Value; 
    strArray = ConvertToStringArray(myvalues); 
    name = clearstr(strArray[1]); 

    for (int j = 1 ; j <= Int32.Parse(number_add_file)*4 ; j++) 
    { 
     name = ""; 
     lang_add = ""; 
     price = ""; 
     description = ""; 
     Console.WriteLine("I got in!"); 

     Microsoft.Office.Interop.Excel.Range range_add = 
      worksheet.get_Range("X" + i.ToString(),Type.Missing); 

     System.Array values = (System.Array)range_add.Cells.Value; 
     string[] str = ConvertToStringArray(values); 
     name = str[0]; 
     lang_add = str[1]; 
     price = str[2]; 
     description = str[3]; 
     Console.WriteLine(name + " " 
      + lang_add + " " + price + " " + description); 

     addfile(); 
    } 

내 질문은 X를 A에서 모든 세포를 읽고이 코드를 가지고 : 나는 "번호"값을 기준으로 Excel에서 4 * "번호"행 다음에 읽을 수 있습니까?

  A B C D E F G H I J 
     a a a a a 1 a a a a 

F의 셀 값이 1 그래서 난 F의 셀 값은 내가 읽고 싶은이 경우 을 (GHIJ)를 읽고 싶은 것입니다 (GHIJKLMN)

  A B C D E F G H I J K L M N 
     a a a a a 2 a a a a a a a a 
: 예를 들어

F의 셀 값 3 :

 A B C D E F G H I J K L M N O P Q R 
     a a a a a 3 a a a a a a a a a a a a 
+0

코드 샘플에서 들여 쓰기를 잘라서 코드를 읽지 않아도되도록하십시오. –

+0

LOL. 또는 우리는 그 사람의 게시물을 간단히 편집 할 수 있습니다 ... – code4life

+0

몇 시간 전에 물어 본 질문과 실질적으로 다른가요? http://stackoverflow.com/questions/9668178/reading-data-from-an-excel-spreadsheet ? – 48klocs

답변

2

이 .NET 4.0입니다 : OU는 쉽게처럼 셀을 참조 할 수

using Excel = Microsoft.Office.Interop.Excel; 
Excel.Application xlApp = new Excel.Application(); 
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("somefile.xls"); 
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1]; // assume it is the first sheet 
Excel.Range xlRange = xlWorksheet.UsedRange; // get the entire used range 
int value = 0; 
if(Int32.TryParse(xlRange.Cells[1,6].Value2.ToString(), out value)) // get the F cell from the first row 
{ 
    int numberOfColumnsToRead = value * 4; 
    for(int col=7; col < (numberOfColumnsToRead + 7); col++) 
    { 
     Console.WriteLine(xlRange.Cells[1,col].Value2.ToString()); // do whatever with value 
    } 
} 

이 통합 문서를 열고 통합 문서의 첫 번째 워크 시트를 얻을 것이다. 그런 다음 사용 된 전체 범위를 가져 와서 범위 변수에 넣습니다. 거기에서 우리는 첫 번째 행에서 "F"열 (6 번째 열, 1이 아닌 1을 기준으로 함)의 int를 구문 분석하려고합니다. 구문 분석에 성공하면 그 수를 4로 곱하여 필요한 열 수를 확인합니다 (게시물에서 행을 말했지만 예제는 열임). for 루프를 사용하여 G 열 (열 7)에서 시작하고 + 7을 읽는 열 수 (건너 뛴 열을 설명하기 위해)로 이동합니다. 값으로 원하는 것을 자유롭게 할 수는 있지만이 예제에서는 콘솔에 씁니다.

+0

코드에서이 오류가 발생합니다. null 참조에서 런타임 바인딩을 수행 할 수 없습니다! – Vlasin

+0

@Vlasin - 사과드립니다. 작성하기 전에 테스트하지 않았습니다. 나는 코드를 수정했고, 나는 그것을 직접 테스트했고, 지금 당신을 위해 작동 할 것이다. – Jetti

0

이 직접 귀하의 질문에 대답하지만, y를 inot입니다

int row1 = 1; 
int row2 = 5; 

sheet1.Cells[row1, row1+row2].Value=row1.ToString(); 
String Rng = Convert.ToString(sheet1.Cells[row1, row2-row1].Address()); 
+0

전혀 관련 없음 ... – Vlasin

0
string testList = ""; 
      String str1 = ""; 
      string logPath = @"E:\LogForConsoleApp.txt"; 
      string filePath = @"E:\SaveSheetName.txt"; 
      string Path = @"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\MSTest"; 
      List<string> ltSheetName = new List<string>(); 
      List<string> ltMethodName = new List<string>(); 
      Process myProcess = new Process(); 
      Excel.Application appExl = new Excel.Application(); 
      Excel.Workbook workbook = null; 
      Excel.Worksheet NwSheet; 
      Excel.Range ShtRange; 
      appExl = new Excel.Application(); 
      workbook = appExl.Workbooks.Open("E:\\inputSheet3", Missing.Value, ReadOnly: false); 
      NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1); 
      ShtRange = NwSheet.UsedRange; //gives the used cells in sheet 
      int rCnt = 0; 
      int cCnt = 0; 

      for (rCnt = 1; rCnt <= ShtRange.Rows.Count; rCnt++) 
      { 
       for (cCnt = 1; cCnt <= ShtRange.Columns.Count; cCnt++) 
       { 
        if (Convert.ToString(NwSheet.Cells[rCnt, cCnt].Value2) == "Y") 
        { 
         ltSheetName.Add(NwSheet.Cells[rCnt, cCnt - 1].Value2); 
         //ltMethodName.Add(" /test:" + NwSheet.Cells[rCnt, cCnt - 1].Value2); 
        } 
       } 
      } 
      workbook.Close(false, Missing.Value, Missing.Value); 
      appExl.Quit(); 

      for (int sht = 0; sht < ltSheetName.Count; sht++) 
      { 
       ltMethodName.Clear(); 
       appExl = new Excel.Application(); 
       workbook = appExl.Workbooks.Open(ltSheetName[sht].ToString(), Missing.Value, ReadOnly: false); 
       NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1); 
       ShtRange = NwSheet.UsedRange; //gives the used cells in sheet 
       int rCnt1 = 0; 
       int cCnt1 = 0; 

       for (rCnt1 = 1; rCnt1 <= ShtRange.Rows.Count; rCnt1++) 
       { 
        for (cCnt1 = 1; cCnt1 <= ShtRange.Columns.Count; cCnt1++) 
        { 
         if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "Y") 
         { 
          ltMethodName.Add(" /test:" + NwSheet.Cells[rCnt, cCnt - 1].Value2); 
         } 
        } 
       } 
       workbook.Close(false, Missing.Value, Missing.Value); 
       appExl.Quit(); 


       for (int i = 0; i < ltMethodName.Count; i++) 
       { 
        str1 = ltMethodName[i].ToString(); 
        testList += str1; 
       } 

       string foldername = "TestResult_" + DateTime.Today.ToString().Remove(DateTime.Today.ToString().LastIndexOf("/") + 5); 
       foldername = foldername.Replace("/", ""); 

       string direc = @"E:\" + foldername; 
       string fileName = ltSheetName[sht].ToString().Substring(ltSheetName[sht].ToString().LastIndexOf("\\") + 1) + "_InderdeepAutRes.trx"; 
       if (!Directory.Exists(direc)) 
        Directory.CreateDirectory(direc); 
       string testcase = ""; 

       if (!File.Exists(direc + "\\" + fileName)) 
        testcase = " /testcontainer:" + "E:\\Practice\\TestingSample\\TestingSample\\bin\\Debug\\TestingSample.dll" + testList + " /resultsfile:" + direc + "\\" + fileName; 
       else 
       { 
        Directory.Delete(direc, true); 
        Directory.CreateDirectory(direc); 
        testcase = " /testcontainer:" + "E:\\Practice\\TestingSample\\TestingSample\\bin\\Debug\\TestingSample.dll" + testList + " /resultsfile:" + direc + "\\" + fileName; 
       } 

       ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(Path, testcase); 

       try 
       { 
        TextWriter tw = new StreamWriter(filePath, false); 
        tw.WriteLine(ltSheetName[sht].ToString()); 
        tw.Close(); 
        myProcess.StartInfo = myProcessStartInfo; 
        myProcessStartInfo.UseShellExecute = false; 
        myProcessStartInfo.RedirectStandardOutput = true; 
        myProcess.Start(); 
        string output = myProcess.StandardOutput.ReadToEnd(); 
        //myProcess.WaitForExit(); 
        Console.WriteLine(output); 

       } 
       catch (Exception ex) 
       { 
        TextWriter tw = new StreamWriter(logPath, true); 
        tw.WriteLine(ex.StackTrace); 
        tw.Close(); 
       } 
      } 
+0

코드가 좋습니다. 왜 그것이 좋은지 설명하는 것은 굉장합니다! 제발 그걸 할 수 있니? –