The following sample demonstrates how to add and remove range comments.
import com.jniwrapper.win32.automation.IDispatch;
import com.jniwrapper.win32.automation.types.Variant;
import com.jniwrapper.win32.excel.Comment;
import com.jniwrapper.win32.excel.Range;
import com.jniwrapper.win32.excel._Worksheet;
import com.jniwrapper.win32.excel.impl.RangeImpl;
import com.jniwrapper.win32.jexcel.Application;
import com.jniwrapper.win32.jexcel.Workbook;
import com.jniwrapper.win32.jexcel.Worksheet;
import java.io.File;
public class RangeCommentSample {
public static final String comment = "My comment";
public static void main(String[] args) throws Exception {
Application application = new Application();
Workbook workbook = application.openWorkbook(new File("comment.xls"));
Worksheet markedSheet = workbook.getWorksheet(1);
final _Worksheet worksheetPeer = markedSheet.getPeer();
markedSheet.getOleMessageLoop().doInvokeAndWait(new Runnable() {
@Override
public void run() {
Range worksheetCells = worksheetPeer.getCells();
long row = 1;
long column = 1;
IDispatch rangeDispatch = worksheetCells.getItem(new Variant(row), new Variant(column)).getPdispVal();
Range range = new RangeImpl(rangeDispatch);
com.jniwrapper.win32.excel.Comment currentComment = range.getComment();
String newComment = comment;
if (currentComment != null && !currentComment.isNull()) {
Variant unspecified = Variant.createUnspecifiedParameter();
newComment = currentComment.text(unspecified, unspecified, unspecified) + "\n" + comment;
// delete old comment: Excel does not allow to add a comment if a
// comment already exists for a particular cell
currentComment.delete();
currentComment.setAutoDelete(false);
currentComment.release();
}
final String commentToBeAdded = newComment;
System.out.println("commentToBeAdded = " + commentToBeAdded);
// create a new comment for this cell
Comment addedComment = range.addComment(new Variant(commentToBeAdded));
addedComment.setAutoDelete(false);
addedComment.release();
range.setAutoDelete(false);
range.release();
rangeDispatch.setAutoDelete(false);
rangeDispatch.release();
worksheetCells.setAutoDelete(false);
worksheetCells.release();
}
});
workbook.save();
application.close(true);
}
}
|
|