试卷导出,poi操作

参考这篇文章,根据实际情况重构代码:

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();
		}
		
	}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Poi是一款开源的Java类库,专门用于处理Microsoft Office文件,包括Excel表格。在使用Poi进行Excel导入导出操作时,我们需要首先在项目中引入Poi的相关依赖库,然后就可以使用Poi提供的API来进行Excel文件的读写操作。 在进行Excel导入时,我们首先要加载Excel文件,可以使用`HSSFWorkbook`或`XSSFWorkbook`类来创建一个Excel对象。然后我们可以通过获取Excel的工作表,使用`getSheetAt(index)`方法可以获取指定位置处的工作表,也可以通过`getSheet(sheetName)`方法来获取指定名称的工作表。接下来,我们可以使用`getRow(rowNum)`方法来获取指定行号的行对象,然后通过`getCell(cellNum)`方法来获取指定列号的单元格对象。通过这些API,我们可以获取到Excel表格中的数据。 在进行Excel导出时,我们首先要创建一个Excel对象,并创建一个工作表,在工作表中创建行和单元格,并将数据写入到单元格中。可以使用`createSheet(sheetName)`方法来创建一个工作表,使用`createRow(rowNum)`方法来创建行对象,使用`createCell(cellNum)`方法来创建单元格对象,然后通过`setCellValue(value)`方法来设置单元格的值。通过这些API,我们可以将数据写入Excel表格中,并最终保存为Excel文件。 Poi提供了丰富的API来处理Excel文件的导入导出操作,包括读取、写入、格式化等功能,使得我们可以轻松地使用Java来操作Excel文件。对于大规模的Excel文件处理,我们还可以使用Poi的SAX模式来进行操作,以提高性能和内存效率。总的来说,使用Poi进行Java Excel导入导出操作是一种灵活、高效的解决方案。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值