2012-03-12 172 views
1

我在使用C#編寫Excel電子表格時遇到了一些麻煩。 我有這樣的代碼,我讀出每一個細胞,從A到X.從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(); 
    } 

我的問題是:我怎麼能以「數量」值,下一個讀取Excel中的4 *「號」行?

例如:

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

F公司細胞值是1,所以我想讀(GHIJ) 若F的單元格的值是2的我想讀取(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

請減少代碼示例中的縮進量,以便我們不必滾動以閱讀代碼。 – 2012-03-12 17:47:09

+0

哈哈。或者我們可以簡單地編輯他的帖子... – code4life 2012-03-12 17:54:52

+0

這是否與你幾個小時前在http://stackoverflow.com/questions/9668178/reading-data-from-an-excel-spreadsheet中提出的問題有實質性的不同? – 48klocs 2012-03-12 18:02:05

回答

2

這是.NET 4.0:

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而不是從零開始)。如果解析成功,我們再將這個數字乘以4,看看你需要多少列(在你的文章中你說過行,但你的例子是列)。我們使用for循環在G列(第7列)處開始並轉到列數以讀取+7(以說明我們跳過的列)。你可以自由地做你想要的值,但對於這個例子,我只是寫了他們到控制檯。

+0

您的代碼會引發此錯誤:無法對空引用執行運行時綁定! – Vlasin 2012-03-13 08:48:49

+0

@Vlasin - 我很抱歉,在寫之前我沒有測試過它。我已經修復了代碼,我只是自己測試它,現在它應該適用於你。代碼很好, – Jetti 2012-03-13 12:53:21

0

這是inot直接回答你的問題,但ÿ OU可以輕鬆地參考您的細胞是這樣的:

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 2012-03-12 18:04:31

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

。解釋爲什麼它是好的!你可以這樣做嗎? – 2015-08-03 09:11:56