2012-12-07 56 views
5

我想讀取Excel表格中的註釋,但無法做到這一點。請幫忙。提前致謝。我的代碼如下 -如何閱讀Excel中的Excel表單的評論#

Excel.Application appExl; 
    Excel.Workbook workbook; 
    Excel.Worksheet NwSheet; 
    Excel.Range ShtRange; 
    appExl = new Excel.Application(); 
    workbook = appExl.Workbooks.Open(Server.MapPath("~/" + System.Configuration.ConfigurationManager.AppSettings["ExcelFile"] + fileName), Missing.Value, Missing.Value, 
    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, 
    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); 
    NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1); 
    string obj = NwSheet.Range[0].Comment.Text;  
+0

乍一看,我會說0不是有效範圍。這不應該是Excel工作表中的有效範圍,例如A6? –

+0

好吧......當然......但我仍然無法將該評論存儲在任何變量中。它給我錯誤 – Priyanka

回答

6

你基本上有過它,但正如Wimbo所說,0不是有效範圍。

從.Net與Office進行互動時,數組總是從一開始。範圍是一個二維數組,所以一旦你有一個範圍,在該範圍內的左上角單元格,像這樣訪問:

using Excel = Microsoft.office.Interop.Excel; 
Excel.Range range = worksheet.Cells[1,1]; 

要訪問以下左上角一個單元格,你可以這樣做:

Excel.Range range = worksheet.Cells[2,1]; //It goes row, then column 

接入小區一到左上角的單元格的權利,你這樣做:

Excel.Range range = worksheet.Cells[1,2]; 

如果你是在.NET 4.0以上工作,你不需要指定可選參數(換句話說,你可以放棄所有的Missing.Value's)。我猜你想在工作簿中得到Sheet 1單元格A1中的註釋,我會這樣做:

using System.Runtime.InteropServices; 
using Excel = Microsoft.Office.Interop.Excel; 

namespace ExcelComments 
{ 
    class Program 
    { 
     static void Main() 
     { 
      var application = new Excel.Application(); 
      var workbook = application.Workbooks.Open(@"C:\Yada yada\workbook with comments.xlsx"); 
      Excel.Worksheet worksheet = workbook.Sheets[1]; 

      Excel.Range range = worksheet.Cells[1, 1]; 

      //Here is your comment as a string 
      var myComment = range.Comment.Text(); 

      workbook.Close(false); 
      application.Quit(); 

      Marshal.ReleaseComObject(application); 
     } 
    } 
} 
+0

非常感謝.....它工作!!!!!再次感謝!!!!! – Priyanka