我正在尝试向 Excel 中的单元格添加注释。我正在使用 jxl 库来做到这一点:
cell = sheet.getWritableCell(1, 2); // cols, rows
WritableCellFeatures wcf = cell.getWritableCellFeatures();
wcf.setComment("comment2");
Run Code Online (Sandbox Code Playgroud)
最后一行返回:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException。尽管进行了多次尝试,但我无法修复它。帮助将不胜感激。谢谢你。
--EDIT--
这是修改后的addNumber方法:
private static void addNumber(WritableSheet sheet, int column, int row,
double d) throws WriteException, RowsExceededException {
Number number;
number = new Number(column, row, d, timesStandard);
//sheet.addCell(number); // need to add the cell first
if (user wants to add a comment) {
WritableCellFeatures wcf = new WritableCellFeatures();
wcf.setComment("the comment");
number.setCellFeatures(wcf);
}
//sheet.addCell(number); // but may need to add the cell with comments as well
}
Run Code Online (Sandbox Code Playgroud)
您之前是否在该位置添加过单元格?问题是您无法在 an 上设置单元格特征EmptyCell,并且它将始终null作为其单元格特征返回。
如果您先添加一个单元格,它就会起作用(为了清楚起见,省略了 try/catch),如下面的代码所示。请注意,它还会首先WritableCellFeatures在新Label单元格上设置 a ,因为最初单元格特征始终为null。
WritableWorkbook book = Workbook.createWorkbook(new File("output.xls"));
WritableSheet sheet = book.createSheet("Some Sheet", 0);
Label label = new Label(1, 2, "Some label");
sheet.addCell(label); // add cell!
WritableCellFeatures wcf = new WritableCellFeatures();
wcf.setComment("Hello!");
// set cell features!
label.setCellFeatures(wcf);
book.write();
book.close();
Run Code Online (Sandbox Code Playgroud)
将其与OP中的方法一起使用:
我修改了方法以返回创建的(和添加的!)Number实例。如果您不希望这样做,您可以使用WritableWorkbook.getWritableCell()相同的行/列来检索相同的单元格。
public static void main(String[] args) throws IOException, RowsExceededException, WriteException {
File file = new File("output.xls");
WritableWorkbook workbook = Workbook.createWorkbook(file);
WritableSheet sheet = workbook.createSheet("First Sheet", 0);
Number number = addNumber(sheet, 3, 2, 565d);
WritableCellFeatures wcf = number.getWritableCellFeatures();
if (wcf == null) wcf = new WritableCellFeatures();
wcf.setComment("the comment");
number.setCellFeatures(wcf);
workbook.write();
workbook.close();
}
private static Number addNumber(WritableSheet sheet, int column, int row,
double d) throws WriteException, RowsExceededException {
Number number = new Number(column, row, d, timesStandard);
sheet.addCell(number); // need to add the cell first
return number;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4859 次 |
| 最近记录: |