最近因为项目需要,对springboot框架整合了基于POI的Word导出和导出功能。功能简单清晰,可以拿来即用,实现方式如下:
POM配置
org.apache.poi poi 3.17org.apache.poi poi-ooxml-schemas 3.17org.apache.poi poi-ooxml 3.17org.apache.poi poi-scratchpad 3.17org.apache.poi poi-scratchpad 3.17fr.opensagres.xdocreport org.apache.poi.xwpf.converter.xhtml 1.0.6
模板示例
Word导出
package com.qingfeng.base.util;import com.qingfeng.util.DateTimeUtil;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.usermodel.Range;import java.io.*;import java.util.ArrayList;import java.util.List;public class WriteDoc { public void testWrite() throws Exception { List list = new ArrayList(); list.add(new Users("a","男","10", DateTimeUtil.getDateTimeStr())); list.add(new Users("b","女","20",DateTimeUtil.getDateTimeStr())); String templatePath = "D:emplate.doc"; InputStream is = new FileInputStream(templatePath); OutputStream os = null; HWPFDocument doc = new HWPFDocument(is); Range range = doc.getRange(); for(int i=0;i
package com.qingfeng.base.util;import org.junit.Test;public class WriteDocTest { @Test public void testWrite() throws Exception { WriteDoc wd = new WriteDoc(); wd.testWrite(); }}
Word导入
package com.qingfeng.base.util;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.usermodel.*;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;public class ReadDoc { public void testReadByDoc(String path) throws Exception { InputStream is = new FileInputStream(path); HWPFDocument doc = new HWPFDocument(is); //输出书签信息 this.printInfo(doc.getBookmarks()); //输出文本 System.out.println(doc.getDocumentText()); Range range = doc.getRange(); this.printInfo(range); //读表格 this.readTable(range); //读列表 this.readList(range); //把当前HWPFDocument写到输出流中 doc.write(new FileOutputStream("D:est.doc")); is.close(); } /** * 输出书签信息 * @param bookmarks */ private void printInfo(Bookmarks bookmarks) { int count = bookmarks.getBookmarksCount(); System.out.println("书签数量:" + count); Bookmark bookmark; for (int i=0; i
package com.qingfeng.base.util;import org.junit.Test;public class ReadDocTest { @Test public void testReadByDoc() throws Exception { ReadDoc rd = new ReadDoc(); rd.testReadByDoc("D:a.doc"); }}
项目下载
青锋项目已经托管到gitee平台,大家可以去下载(搜索:青锋后台管理系统),或者点击下方了解更多,或者私信都可以去下载。