5

我正在尝试阅读 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;    
4

1 回答 1

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 或更高版本中工作,则无需指定可选参数(换句话说,您可以删除所有Missing.Value)。我猜你想在工作簿的第 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);
        }
    }
}
于 2012-12-07T11:24:58.130 回答