Reputation: 365
i am trying to read the comments from excel sheet but unable to do so. Please help. Thanks in advance. my code is as follows-
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;
Upvotes: 4
Views: 7528
Reputation: 28079
You basically had it, but as Wimbo said, 0 isn't a valid range.
When interoping with Office from .Net, arrays always start at one. A range is a 2D array, so once you have a range, the top left cell in that Range is accessed like so:
using Excel = Microsoft.office.Interop.Excel;
Excel.Range range = worksheet.Cells[1,1];
To access the cell below the top left one, you would do this:
Excel.Range range = worksheet.Cells[2,1]; //It goes row, then column
To access the cell one to the right of the top left cell, you do this:
Excel.Range range = worksheet.Cells[1,2];
If you are working in .Net 4 or above, you don't need to specify the optional parameters (in otherwords you can drop all of the Missing.Value's). I'm guessing you want to get the comment in Cell A1 on Sheet 1 in a workbook, I would do this like so:
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);
}
}
}
Upvotes: 5