参考这篇文章,根据实际情况重构代码:
http://53873039oycg.iteye.com/blog/2153194
import java.io.FileOutputStream;
import java.math.BigInteger;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.TextAlignment;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHpsMeasure;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule;
/**
* 试卷导出
* @author
*/
public class TestPaperExportUtil {
/**
* 设置title
* @param document
* @param title
*/
public static void setTilte(CustomXWPFDocument_S_2 document, String title) {
XWPFParagraph p = document.createParagraph();
setTextFontInfo(p, false, false, title, "宋体", "000000",
"40", true, null, false, false, null, 0, null);
setParagraphSpacingInfo(p, true, "0", "0", "0", "0", true, "240",
STLineSpacingRule.Enum.forString("auto"));
setParagraphAlignInfo(p, ParagraphAlignment.CENTER,
TextAlignment.CENTER);
}
/**
* 设置班级,姓名
* @param document
* @param Bj
*/
public static void setBJ(CustomXWPFDocument_S_2 document, String Bj){
Bj = "班级:________ 姓名:________";
XWPFParagraph p = document.createParagraph();
setTextFontInfo(p, false, false, Bj, "宋体",
"000000", "21", false, null, false, false, null, 0,null);
setParagraphSpacingInfo(p, true, "0", "0", "0", "0", true, "240",
STLineSpacingRule.Enum.forString("auto"));
setParagraphAlignInfo(p, ParagraphAlignment.CENTER,
TextAlignment.CENTER);
}
/**
* 设置题组名称
* @param document
* @param qGName
*/
public static void setQuestionGroup(CustomXWPFDocument_S_2 document, String qGName){
XWPFParagraph p = document.createParagraph();
setTextFontInfo(p, false, false, qGName, "宋体", "000000",
"21", true, null, false, false, null, 0,null);
setParagraphSpacingInfo(p, true, "0", "0", "100", null, true, "240",
STLineSpacingRule.Enum.forString("auto"));
setParagraphAlignInfo(p, ParagraphAlignment.LEFT, TextAlignment.CENTER);
}
/**
* 设置题名称
* @param document
* @param qName
*/
public static void setQuestion(CustomXWPFDocument_S_2 document, String qName){
XWPFParagraph p = document.createParagraph();
setTextFontInfo(p, false, false, qName, "宋体",
"000000", "21", false, null, false, false, null, 0,null);
setParagraphSpacingInfo(p, true, "0", "0", "0", "0", true, "240",
STLineSpacingRule.Enum.forString("auto"));
setParagraphAlignInfo(p, ParagraphAlignment.LEFT, TextAlignment.CENTER);
}
/**
* @param verticalAlign
* SUPERSCRIPT上标 SUBSCRIPT下标
* @param position
* 字符位置 1磅=2
*/
// 设置字体信息 设置字符间距信息(CTSignedTwipsMeasure)
public static void setTextFontInfo(XWPFParagraph p, boolean isInsert,
boolean isNewLine, String content, String fontFamily,
String colorVal, String fontSize, boolean isBlod,
UnderlinePatterns underPatterns, boolean isItalic,
boolean isStrike, VerticalAlign verticalAlign, int position,
String spacingValue) {
XWPFRun pRun = null;
if (isInsert) {
pRun = p.createRun();
} else {
if (p.getRuns() != null && p.getRuns().size() > 0) {
pRun = p.getRuns().get(0);
} else {
pRun = p.createRun();
}
}
if (isNewLine) {
pRun.addBreak();
}
pRun.setText(content);
// 设置字体样式
pRun.setBold(isBlod);
pRun.setItalic(isItalic);
pRun.setStrike(isStrike);
if (underPatterns != null) {
pRun.setUnderline(underPatterns);
}
pRun.setColor(colorVal);
if (verticalAlign != null) {
pRun.setSubscript(verticalAlign);
}
pRun.setTextPosition(position);
CTRPr pRpr = null;
if (pRun.getCTR() != null) {
pRpr = pRun.getCTR().getRPr();
if (pRpr == null) {
pRpr = pRun.getCTR().addNewRPr();
}
} else {
// pRpr = p.getCTP().addNewR().addNewRPr();
}
// 设置字体
CTFonts fonts = pRpr.isSetRFonts() ? pRpr.getRFonts() : pRpr
.addNewRFonts();
fonts.setAscii(fontFamily);
fonts.setEastAsia(fontFamily);
fonts.setHAnsi(fontFamily);
// 设置字体大小
CTHpsMeasure sz = pRpr.isSetSz() ? pRpr.getSz() : pRpr.addNewSz();
sz.setVal(new BigInteger(fontSize));
CTHpsMeasure szCs = pRpr.isSetSzCs() ? pRpr.getSzCs() : pRpr
.addNewSzCs();
szCs.setVal(new BigInteger(fontSize));
/*
* if(spacingValue!=null){ //设置字符间距信息 CTSignedTwipsMeasure
* ctSTwipsMeasure=pRpr.isSetSpacing()?pRpr.getSpacing():
* pRpr.addNewSpacing(); ctSTwipsMeasure.setVal(new
* BigInteger(spacingValue)); }
*/
}
public static void addNewPage(XWPFDocument document, BreakType breakType) {
XWPFParagraph xp = document.createParagraph();
xp.createRun().addBreak(breakType);
}
public static void saveDocument(XWPFDocument document, String savePath)
throws Exception {
FileOutputStream fos = new FileOutputStream(savePath);
document.write(fos);
fos.close();
}
// 设置段落间距信息
// 一行=100 一磅=20
public static void setParagraphSpacingInfo(XWPFParagraph p, boolean isSpace,
String before, String after, String beforeLines, String afterLines,
boolean isLine, String line, STLineSpacingRule.Enum lineValue) {
CTPPr pPPr = null;
if (p.getCTP() != null) {
if (p.getCTP().getPPr() != null) {
pPPr = p.getCTP().getPPr();
} else {
pPPr = p.getCTP().addNewPPr();
}
}
CTSpacing pSpacing = pPPr.getSpacing() != null ? pPPr.getSpacing()
: pPPr.addNewSpacing();
if (isSpace) {
// 段前磅数
if (before != null) {
pSpacing.setBefore(new BigInteger(before));
}
// 段后磅数
if (after != null) {
pSpacing.setAfter(new BigInteger(after));
}
// 段前行数
if (beforeLines != null) {
pSpacing.setBeforeLines(new BigInteger(beforeLines));
}
// 段后行数
if (afterLines != null) {
pSpacing.setAfterLines(new BigInteger(afterLines));
}
}
if (isLine) {
if (line != null) {
pSpacing.setLine(new BigInteger(line));
}
if (lineValue != null) {
pSpacing.setLineRule(lineValue);
}
}
}
// 设置段落对齐
public static void setParagraphAlignInfo(XWPFParagraph p,
ParagraphAlignment pAlign, TextAlignment valign) {
p.setAlignment(pAlign);
p.setVerticalAlignment(valign);
}
}
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
public class CustomXWPFDocument_S_2 extends XWPFDocument {
public CustomXWPFDocument_S_2() {
super();
}
public CustomXWPFDocument_S_2(InputStream in) throws IOException {
super(in);
}
public CustomXWPFDocument_S_2(OPCPackage pkg) throws IOException {
super(pkg);
}
public void createPicture(String blipId, int id, int width, int height,
XWPFParagraph paragraph) {
final int EMU = 9525;
width *= EMU;
height *= EMU;
// String blipId =
// getAllPictures().get(id).getPackageRelationship().getId();
if (paragraph == null) {
paragraph = createParagraph();
}
CTInline inline = paragraph.createRun().getCTR().addNewDrawing()
.addNewInline();
String picXml = ""
+ "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
+ " <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
+ " <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
+ " <pic:nvPicPr>" + " <pic:cNvPr id=\""
+ id
+ "\" name=\"img_"
+ id
+ "\"/>"
+ " <pic:cNvPicPr/>"
+ " </pic:nvPicPr>"
+ " <pic:blipFill>"
+ " <a:blip r:embed=\""
+ blipId
+ "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
+ " <a:stretch>"
+ " <a:fillRect/>"
+ " </a:stretch>"
+ " </pic:blipFill>"
+ " <pic:spPr>"
+ " <a:xfrm>"
+ " <a:off x=\"0\" y=\"0\"/>"
+ " <a:ext cx=\""
+ width
+ "\" cy=\""
+ height
+ "\"/>"
+ " </a:xfrm>"
+ " <a:prstGeom prst=\"rect\">"
+ " <a:avLst/>"
+ " </a:prstGeom>"
+ " </pic:spPr>"
+ " </pic:pic>"
+ " </a:graphicData>" + "</a:graphic>";
// CTGraphicalObjectData graphicData =
// inline.addNewGraphic().addNewGraphicData();
XmlToken xmlToken = null;
try {
xmlToken = XmlToken.Factory.parse(picXml);
} catch (XmlException xe) {
xe.printStackTrace();
}
inline.set(xmlToken);
// graphicData.set(xmlToken);
inline.setDistT(0);
inline.setDistB(0);
inline.setDistL(0);
inline.setDistR(0);
CTPositiveSize2D extent = inline.addNewExtent();
extent.setCx(width);
extent.setCy(height);
CTNonVisualDrawingProps docPr = inline.addNewDocPr();
docPr.setId(id);
docPr.setName("img_ " + id);
docPr.setDescr("Picture");
}
}
@RequestMapping(value = "/{id}/export", method = RequestMethod.GET)
public String export(SimpleQuery query, @PathVariable long id)
throws Exception {
testPaperService.export(id, "");
return "redirect:/builder/questions/testPaper";
}
TestPaperServiceimpl:
/**
* 读取word
* @param path
* @return
*/
@Override
public String wordRead(String path){
File file = new File(path);
String text = "";
try {
FileInputStream fis = new FileInputStream(file);
WordExtractor wordExtractor = new WordExtractor(fis);
text = wordExtractor.getText();
XWPFDocument doc = new XWPFDocument(fis);
List<XWPFParagraph> paras = doc.getParagraphs();
for (XWPFParagraph para : paras) {
System.out.println(para.getText());
}
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
/*@Override
public List<XWPFParagraph> getWord(String path){
File file = new File(path);
List<XWPFParagraph> paras = Lists.newArrayList();
try {
FileInputStream fis = new FileInputStream(file);
XWPFDocument doc = new XWPFDocument(fis);
paras = doc.getParagraphs();
} catch (IOException e) {
e.printStackTrace();
}
return paras;
}*/
/**
* 获取标签中的内容
* @param text
* @param tag
* @return
*/
@Override
public String getTagContent(String text,String tag){
String bt = "";
int btIndex = text.indexOf("<"+tag+">");
int btLastIndex = text.indexOf("</"+tag+">");
if(btIndex!=-1&&btLastIndex!=-1){
bt = text.substring(btIndex+("<"+tag+">").length(), btLastIndex);
}
return bt;
}
/**
* 获取某一组的某一个单项,如单选题这个组别中有多个单选题(单项)
* @param text
* @param tag1 单项标签名,(例如:题)
* @param tag2 上面标签的名称或者其他什么(标签)
* @return
*/
@Override
public void getSingleContent(String text,String tag1,String tag2,String questionType,Resource testPaper){
for(int i = 1;i>=1;i++){
String tContent = getTagContent(text,tag1+i);
String tMc = getTagContent(tContent,tag2);
if(Strings.isNullOrEmpty(tContent)||Strings.isNullOrEmpty(tMc)) break;
if(i18n(XZT).equals(questionType)){
for(int j = 1;j>=1;j++){
String xxContent = getTagContent(tContent,i18n(XX));
String cContent = getTagContent(xxContent,i18n(CONTENT));
if(Strings.isNullOrEmpty(xxContent)||Strings.isNullOrEmpty(cContent)) break;
System.out.println(cContent);
}
}
//下面再做添加操作
System.out.println(tMc);
Resource question = new Resource();
ResourceType resourceType = resourceTypeDao.findByCode(TypeCode.QUESTION);
question.setDescription(tMc);
question.setType(resourceType);
save(question);
String daMc = getTagContent(tContent,i18n(TestPaperService.DA));
this.saveExValue(question, "rightAnswer", daMc);
this.saveExValue(question, "questionType", questionType);
List<Resource> questions = testPaper.getItems();
if(questions==null){
questions = Lists.newArrayList();
questions.add(question);
testPaper.setItems(questions);
}else{
testPaper.getItems().add(question);
}
resourceDao.update(testPaper);
}
}
/**
* 设置资源中某个字段的value
* @param resource 资源
* @param fieldName 字段名称
* @param value 值
*/
protected void saveExValue(Resource resource, String fieldName, String value){
ExField rAField = exFieldDao.findByNameAndType(fieldName, resource.getType().getId());
ExValue rAValue = new ExValue();
rAValue.setField(rAField);
rAValue.setResource(resource);
rAValue.setValue(value);
exValueDao.save(rAValue);
}
protected String i18n(String message) {
return messageSource.getMessage(message, null, null);
}
@Override
public void importQuestions(String text) {
//--------------------------------标题------------------------------------
String btContent = this.getTagContent(text,i18n(TestPaperService.BT));
String btMc = this.getTagContent(btContent,i18n(TestPaperService.MC));
System.out.println(btMc);
Resource testPaper = new Resource();
testPaper.setName(btMc);
ResourceType testPaperType = resourceTypeDao.findByCode(TypeCode.TEST_PAPER);
testPaper.setType(testPaperType);
this.save(testPaper);
//----------------------------------选择题---------------------------------------
String xztContent = this.getTagContent(text,i18n(TestPaperService.XZT));
String xztMc = this.getTagContent(xztContent,i18n(TestPaperService.MC));
System.out.println(xztMc);
this.getSingleContent(xztContent,i18n(TestPaperService.T),i18n(TestPaperService.MC),i18n(TestPaperService.XZT),testPaper);
//----------------------------------判断题---------------------------------------
String pdtContent = this.getTagContent(text,i18n(TestPaperService.PDT));
String pdtMc = this.getTagContent(pdtContent,i18n(TestPaperService.MC));
System.out.println(pdtMc);
this.getSingleContent(pdtContent,i18n(TestPaperService.T),i18n(TestPaperService.MC),i18n(TestPaperService.PDT),testPaper);
//----------------------------------填空题---------------------------------------
String tktContent = this.getTagContent(text,i18n(TestPaperService.TKT));
String tktMc = this.getTagContent(tktContent,i18n(TestPaperService.MC));
System.out.println(tktMc);
this.getSingleContent(tktContent,i18n(TestPaperService.T),i18n(TestPaperService.MC),i18n(TestPaperService.TKT),testPaper);
//----------------------------------解答题---------------------------------------
String jdtContent = this.getTagContent(text,i18n(TestPaperService.WDT));
String jdtMc = this.getTagContent(jdtContent,i18n(TestPaperService.MC));
System.out.println(jdtMc);
this.getSingleContent(jdtContent,i18n(TestPaperService.T),i18n(TestPaperService.MC),i18n(TestPaperService.WDT),testPaper);
}
@Override
public void export(long id, String path) {
Resource testPaper = findById(id);
path = "D:\\" + testPaper.getName()+".doc";
CustomXWPFDocument_S_2 document = new CustomXWPFDocument_S_2();
String tPName = testPaper.getName();
TestPaperExportUtil.setTilte(document, tPName);
TestPaperExportUtil.setBJ(document,"");
// 题组
SimpleQuery query = new SimpleQuery();
List<Resource> questionGroups = this.listByParentIdAndCode(query, id, TypeCode.QUESTION_GROUP);
for (Resource questionGroup : questionGroups) {
Object value = questionGroup.getMap().get("questionType");
String qTString = String.valueOf(value);
List<Resource> questions = questionDao.listQuestionByTypeAndPaper(qTString, id);
if (questions != null && !questions.isEmpty()) {
System.out.println(questionGroup.getName());
TestPaperExportUtil.setQuestionGroup(document, questionGroup.getName());
}
for (Resource question : questions) {
System.out.println(question.getDescription());
TestPaperExportUtil.setQuestion(document, question.getDescription());
}
}
try {
TestPaperExportUtil.saveDocument(document,path);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}