我是使用docx4j的新手,我试图了解反向工程XLSX文档。我试图在单元格A1中的工作表中添加注释,然后我使用在线代码生成器并在下面进行了正在进行的工作。我有一个生成CTComments的方法,但我想我需要把它变成一个CommentPart?我调用什么对象来添加CommentPart?
import javax.xml.bind.JAXBException;
import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.packages.SpreadsheetMLPackage;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.SpreadsheetML.CommentsPart;
import org.docx4j.openpackaging.parts.SpreadsheetML.WorksheetPart;
import org.xlsx4j.jaxb.Context;
import org.xlsx4j.sml.CTComments;
import org.xlsx4j.sml.CTRst;
import org.xlsx4j.sml.CTXstringWhitespace;
import org.xlsx4j.sml.Cell;
import org.xlsx4j.sml.Row;
import org.xlsx4j.sml.STCellType;
import org.xlsx4j.sml.SheetData;
public class launch {
public static void main(String[] args)
{
try {
String outputfilepath = "C:\\temp\\OUT_CreateSimpleSpreadsheet.xlsx";
SpreadsheetMLPackage pkg = SpreadsheetMLPackage.createPackage();
WorksheetPart sheet = pkg.createWorksheetPart(new PartName("/xl/worksheets/sheet1.xml"), "Sheet1", 1);
addContent(sheet);
pkg.save(new File(outputfilepath));
System.out.println("\n\n done .. " + outputfilepath);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void addContent(WorksheetPart sheet) {
// Minimal content already present
SheetData sheetData = sheet.getJaxbElement().getSheetData();
// Now add
Row row = Context.getsmlObjectFactory().createRow();
Cell cell = Context.getsmlObjectFactory().createCell();
cell.setV("1234");
row.getC().add(cell);
row.getC().add(createCell("hello world!"));
//HOW DO I ADD A COMMENT TO THIS CELL?
sheetData.getRow().add(row);
}
private static Cell createCell(String content) {
Cell cell = Context.getsmlObjectFactory().createCell();
CTXstringWhitespace ctx = Context.getsmlObjectFactory().createCTXstringWhitespace();
ctx.setValue(content);
CTRst ctrst = new CTRst();
ctrst.setT(ctx);
cell.setT(STCellType.INLINE_STR);
cell.setIs(ctrst); // add ctrst as inline string
return cell;
}
public static CTComments createComment() throws JAXBException {
String openXML = "<comments>"
+ "<authors>"
+ "<author>Author</author>"
+"</authors>"
+ "<commentList>"
+ "<comment authorId=\"0\" ref=\"A1\">"
+ "<text>"
+ "<r>"
+ "<rPr>"
+ "<b/>"
+ "<sz val=\"9\"/>"
+ "<color indexed=\"81\"/>"
+ "<rFont val=\"Tahoma\"/>"
+ "<charset val=\"1\"/>"
+"</rPr>"
+ "<t>Thomas: hello world!</t>"
+"</r>"
+"</text>"
+"</comment>"
+"</commentList>"
+"</comments>";
CTComments comments = (CTComments)XmlUtils.unmarshalString(openXML);
return comments;
}
}
答案 0 :(得分:2)
是的,你走在正确的轨道上。
我已经充实了您的代码并在samples/XlsxAddComment.java提交了一个完整的示例
您将在那里看到如何添加CommentsPart。
还需要VMLPart;每个评论都有一个元素。其中,x:Row和x:Column值必须对应于comment / @ ref。例如,第0行,col 0 = ref A1。