1:須要的jar包html
百度雲: https://pan.baidu.com/s/1TP9YWhTQu8QHpB41AU3I5Q 提取碼: ymtj 前端
maven:java
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.3</version>
</dependency>web
2:作法 建立一個Java工程-------引入夾包------寫個測試類測試,以下圖大概結構apache
3:類代碼寫法以下,作法:在d盤下放個圖片 例如:D:\\123.jpg , 直接建立一個類,把代碼所有粘過去, 運行main方法,看D盤生成的文件api
//*********************************類代碼寫法開始*************************************maven
package com;測試
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;字體
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
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;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;網站
/**
* 一些其餘的網站寫法
* https://elim.iteye.com/blog/2049110
* https://www.cnblogs.com/unruly/archive/2017/09/06/7483858.html
* https://www.cnblogs.com/zyc-blogs/p/10558859.html
* https://blog.csdn.net/ztt_1119/article/details/69390807
* http://poi.apache.org/apidocs/dev/org/apache/poi/xwpf/usermodel/XWPFTable.html
* https://blog.csdn.net/ztt_1119/article/details/69390807
* https://www.cnblogs.com/sun-flower1314/p/10128796.html
* https://wenku.baidu.com/view/2507cb89905f804d2b160b4e767f5acfa0c78336.html
* https://53873039oycg.iteye.com/blog/2157923
* https://www.cnblogs.com/dayuruozhi/p/6490868.html
* https://www.cnblogs.com/AardWolf/p/11268068.html
* https://blog.csdn.net/owen_william/article/details/81290024
*
*
*
*/
public class TestWord1 extends XWPFDocument{
//初始化XWPFDocument
public static XWPFDocument initDoc(List<Map<String,Object>> list) throws Exception{
XWPFDocument document = new XWPFDocument();
//設置邊距
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
CTPageMar pageMar = sectPr.addNewPgMar();
pageMar.setLeft(BigInteger.valueOf(720L));
pageMar.setTop(BigInteger.valueOf(1440L));
pageMar.setRight(BigInteger.valueOf(720L));
pageMar.setBottom(BigInteger.valueOf(1440L));
//================插入圖片======================
XWPFParagraph pictures = document.createParagraph();
pictures.setIndentationLeft(300);//前面縮進300
XWPFRun insertNewRun = pictures.createRun();
int format =0;
String imgFile ="D:\\123.jpg";
if(imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
else if(imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
else if(imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT;
else if(imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG;
else if(imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG;
else if(imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
else if(imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
else if(imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
else if(imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
else if(imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
else if(imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
else {
System.err.println("Unsupported picture: " + imgFile +
". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
}
insertNewRun.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(350), Units.toEMU(150)); //高150,寬350
// insertNewRun.addBreak(BreakType.PAGE);//圖片獨佔一頁
insertNewRun.addBreak();//添加一個回車空行
//====================設置段落======================
XWPFParagraph firstParagraph = document.createParagraph();
firstParagraph.setAlignment(ParagraphAlignment.RIGHT);//設置段落內容靠右
firstParagraph.setIndentationRight(500);//末尾縮進300
XWPFRun run = firstParagraph.createRun();
run.setText("測試段落 樣式設置");
run.setBold(true); //加粗
run.setFontSize(12);//字體大小
run.setFontFamily("華文中宋");
run.addBreak();//添加一個回車空行
//============添加標題====================
XWPFParagraph titleParagraph = document.createParagraph();
//設置段落居中
titleParagraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleParagraphRun = titleParagraph.createRun();
titleParagraphRun.setText("測試使用poi導出word");
titleParagraphRun.setBold(true);//加粗
titleParagraphRun.setFontSize(22);//字體大小
titleParagraphRun.setFontFamily("華文中宋");
titleParagraphRun.addBreak();
//==============添加表格數據===========
//數據表格
XWPFTable ComTable = document.createTable();//默認建立一個一行一列的表格
//===========表格表頭行===============
XWPFTableRow titleRow = ComTable.getRow(0);//建立的的一行一列的表格,獲取第一行
titleRow.setHeight(500);//設置當前行行高
titleStyle(titleRow);//設置表頭行樣式和內容
//將數據封裝到表格中
for(Map<String,Object> m:list){
//=============合併行----合併單位名稱======================
XWPFTableRow DWMCRow = ComTable.createRow();//建立表頭行下新的一行,列數是按照表頭行的列數建立的
DWMCRow.setHeight(600);//設置行高
//獲取當前行的列數,原理第一行有幾列,下面建立的新行就有幾列,若是建立表格時指定了,就按指定的數建立多少列
List<XWPFTableCell> DWMCCellList = DWMCRow.getTableCells();
for (int i = 0; i < DWMCCellList.size(); i++) {//通過這個循環後就將這一行的全部列合併成一列了
//對單元格進行合併的時候,要標誌單元格是否爲起點,或者是否爲繼續合併
if (i == 0)
DWMCCellList.get(i).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);//這是起點
else
DWMCCellList.get(i).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);//繼續合併
}
XWPFTableCell DWMCCell = DWMCCellList.get(0);//當前行合併成一列了,獲取這一列
TitleCelldata1(DWMCCell,m.get("dwmc")==null?"無":m.get("dwmc").toString());//給列添加樣式和數據
//=================================遍歷具體的數據===============================
List<Map<String,Object>> list1 = (List<Map<String,Object>>)m.get("data");
int i=0;
for(Map<String,Object> dm:list1){
XWPFTableRow dataRow = ComTable.createRow();//建立一個新的行
dataRow.setHeight(500);//設置行高
List<XWPFTableCell> DataCellList = dataRow.getTableCells();//獲取建立行的全部的列
XWPFTableCell tc0 = DataCellList.get(0);//獲取建立行的第一列
CelldataCss(tc0,"800");//給第一列序號添加樣式
tc0.setText(++i+"");//給第一列添加值
for(int ci=1;ci<DataCellList.size();ci++){//循環給剩下的列賦值
XWPFTableCell tc = DataCellList.get(ci);
//CelldataCss(tc,"1300");//給列添加樣式
CellData(dm, tc, ci);//填充數據
}
}
}
return document;
}
//設置表頭行樣式和內容
public static void titleStyle(XWPFTableRow titleRow){
XWPFTableCell xhCell = titleRow.getCell(0);//建立的表格沒有指定幾行幾列,就默認是一行一列,這裏獲取建立的第一列
xhCell.setText("");
CelldataCss(xhCell,"800");
XWPFTableCell bmCell =titleRow.addNewTableCell();//在當前行繼續建立新列
TitleCelldata(bmCell,"部門");
XWPFTableCell xmCell =titleRow.addNewTableCell();
TitleCelldata(xmCell,"姓名");
XWPFTableCell zwCell =titleRow.addNewTableCell();
TitleCelldata(zwCell,"職務");
XWPFTableCell bgdhCell =titleRow.addNewTableCell();
TitleCelldata(bgdhCell,"辦公電話");
XWPFTableCell sjhmCell =titleRow.addNewTableCell();
TitleCelldata(sjhmCell,"手機號碼");
XWPFTableCell yxCell =titleRow.addNewTableCell();
TitleCelldata(yxCell,"郵箱");
}
//設置數據列樣式
public static void CelldataCss(XWPFTableCell cell,String width){
/** 設置水平居中 */
CTTc cttc = cell.getCTTc();
CTTcPr ctPr = cttc.addNewTcPr();
ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);//上下居中
cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);//左右居中
CTTblWidth tblWidth = ctPr.isSetTcW() ? ctPr.getTcW() : ctPr.addNewTcW();
tblWidth.setW(new BigInteger(width));//設置列寬度
tblWidth.setType(STTblWidth.DXA);
}
//設置內容信息樣式
public static void dataCelldata(XWPFTableCell cell,String txt,String tname){
//給當前列中添加段落,就是給列添加內容
XWPFParagraph p = cell.getParagraphs().get(0);
XWPFRun headRun0 = p.createRun();
headRun0.setText(txt);//設置內容
headRun0.setFontSize(11);//設置大小
// headRun0.setBold(true);//是否粗體
headRun0.setFontFamily("仿宋_GB2312");
//給列中的內容設置樣式
CTTc cttc = cell.getCTTc();
CTTcPr ctPr = cttc.addNewTcPr();
ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);//上下居中
cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);//左右居中
CTTblWidth tblWidth = ctPr.isSetTcW() ? ctPr.getTcW() : ctPr.addNewTcW();
if("zw".equals(tname)){
tblWidth.setW(new BigInteger("2050"));//設置列寬度
}else{
tblWidth.setW(new BigInteger("1600"));//設置列寬度
}
tblWidth.setType(STTblWidth.DXA);
}
//設置表頭和單位信息樣式
public static void TitleCelldata(XWPFTableCell cell,String txt){
//給當前列中添加段落,就是給列添加內容
XWPFParagraph p = cell.getParagraphs().get(0);
XWPFRun headRun0 = p.createRun();
headRun0.setText(txt);//設置內容
headRun0.setFontSize(12);//設置大小
headRun0.setBold(true);//是否粗體
headRun0.setFontFamily("華文中宋");
//給列中的內容設置樣式
CTTc cttc = cell.getCTTc();
CTTcPr ctPr = cttc.addNewTcPr();
ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);//上下居中
cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);//左右居中
CTTblWidth tblWidth = ctPr.isSetTcW() ? ctPr.getTcW() : ctPr.addNewTcW();
if("職務".equals(txt)){
tblWidth.setW(new BigInteger("2050"));//設置列寬度
}else{
tblWidth.setW(new BigInteger("1600"));//設置列寬度
}
tblWidth.setType(STTblWidth.DXA);
}
//設置表頭和單位信息樣式
public static void TitleCelldata1(XWPFTableCell cell,String txt){
//給當前列中添加段落,就是給列添加內容
XWPFParagraph p = cell.getParagraphs().get(0);
XWPFRun headRun0 = p.createRun();
headRun0.setText(txt);//設置內容
headRun0.setFontSize(12);//設置大小
headRun0.setBold(true);//是否粗體
headRun0.setFontFamily("華文中宋");
//給列中的內容設置樣式
CTTc cttc = cell.getCTTc();
CTTcPr ctPr = cttc.addNewTcPr();
ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);//上下居中
cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);//左右居中
CTTblWidth tblWidth = ctPr.isSetTcW() ? ctPr.getTcW() : ctPr.addNewTcW();
tblWidth.setW(new BigInteger(1600*6+800+450+""));//設置列寬度
tblWidth.setType(STTblWidth.DXA);
cell.setColor("DCDCDC");
}
//將數據賦值到每一列上
public static void CellData(Map<String,Object> m,XWPFTableCell cell,Integer ic){
switch(ic){
case 1:
dataCelldata(cell, m.get("bm")==null?"無":m.get("bm").toString(),"bm");
break;
case 2:
dataCelldata(cell, m.get("mc")==null?"無":m.get("mc").toString(),"mc");
break;
case 3:
dataCelldata(cell, m.get("zw")==null?"無":m.get("zw").toString(),"zw");
break;
case 4:
dataCelldata(cell, m.get("bgdh")==null?"無":m.get("bgdh").toString(),"bgdh");
break;
case 5:
dataCelldata(cell, m.get("sjhm")==null?"無":m.get("sjhm").toString(),"sjhm");
break;
case 6:
dataCelldata(cell, m.get("yx")==null?"無":m.get("yx").toString(),"yx");
break;
}
}
//手動構造數據
public static List<Map<String,Object>> data(){
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String,Object> m1 = new HashMap<String,Object>();
m1.put("dwmc", "測試部門1");
List<Map<String,Object>> list1 = new ArrayList<Map<String,Object>>();
for(int i=0;i<5;i++){
Map<String,Object> d1 = new HashMap<String,Object>();
d1.put("bm", "部門"+i);//部門
d1.put("mc", "名稱"+i);//名稱
d1.put("zw", "職務"+i);//職務
d1.put("bgdh", "辦公電話"+i);//辦公電話
d1.put("sjhm", "手機號碼"+i);//手機號碼
d1.put("yx", "郵箱"+i);//郵箱
d1.put("xh", i+1);//序號
list1.add(d1);
}
m1.put("data", list1);
Map<String,Object> m2 = new HashMap<String,Object>();
m2.put("dwmc", "測試部門2");
List<Map<String,Object>> list2 = new ArrayList<Map<String,Object>>();
for(int i=0;i<3;i++){
Map<String,Object> d1 = new HashMap<String,Object>();
d1.put("bm", "部門"+i);//部門
d1.put("mc", "名稱"+i);//名稱
d1.put("zw", "職務"+i);//職務
d1.put("bgdh", "辦反反覆覆煩煩煩煩煩煩煩煩煩煩煩煩煩煩煩吼吼吼吼吼吼吼吼吼吼吼吼吼吼吼吼公電話"+i);//辦公電話
d1.put("sjhm", "手機號碼"+i);//手機號碼
d1.put("yx", "郵箱"+i);//郵箱
d1.put("xh", i+1);//序號
list2.add(d1);
}
m2.put("data", list2);
Map<String,Object> m3 = new HashMap<String,Object>();
m3.put("dwmc", "測試部門3");
List<Map<String,Object>> list3 = new ArrayList<Map<String,Object>>();
for(int i=0;i<2;i++){
Map<String,Object> d1 = new HashMap<String,Object>();
d1.put("bm", "部門"+i);//部門
d1.put("mc", "名稱"+i);//名稱
d1.put("zw", "職務"+i);//職務
d1.put("bgdh", "辦公電話"+i);//辦公電話
d1.put("sjhm", "手機號碼"+i);//手機號碼
d1.put("yx", "郵箱"+i);//郵箱
d1.put("xh", i+1);//序號
list3.add(d1);
}
m3.put("data", list3);
list.add(m1);
list.add(m2);
list.add(m3);
return list;
}
/**
* insert Picture
* @param document
* @param filePath
* @param inline
* @param width
* @param height
* @throws InvalidFormatException
* @throws FileNotFoundException
*/
private static void insertPicture(XWPFDocument document, String filePath,CTInline inline, int width, int height) throws InvalidFormatException,
FileNotFoundException {
document.addPictureData(new FileInputStream(filePath),XWPFDocument.PICTURE_TYPE_PNG);
int id = document.getAllPictures().size() - 1;
final int EMU = 9525;
width *= EMU;
height *= EMU;
// String blipId = document.getAllPictures().get(id).getPackageRelationship().getId();
// blipId =document.addPictureData(fastDFSClient.download(src),Document.PICTURE_TYPE_PNG);
//String blipId = document.getAllPictures().get(id).getPackageRelationship().getId();
String blipId = document.getAllPackagePictures().get(id).getRelationId(document.getAllPackagePictures().get(id).getParent());
String picXml = getPicXml(blipId, width, height);
XmlToken xmlToken = null;
try {
xmlToken = XmlToken.Factory.parse(picXml);
} catch (XmlException xe) {
xe.printStackTrace();
}
inline.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("IMG_" + id);
}
/**
* get the xml of the picture
* @param blipId
* @param width
* @param height
* @return
*/
private static String getPicXml(String blipId, int width, int height) {
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=\"" + 0 +
"\" name=\"Generated\"/>" + " <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>";
return picXml;
}
public static void main(String[] args) throws Exception {
XWPFDocument document= initDoc(data());
FileOutputStream out = new FileOutputStream("d:\\部門通信錄.docx");
document.write(out);
out.close();
System.out.println("導出成功!!!!!!!!");
}
}
//*********************************類代碼寫法結束*************************************
4:生成的效果
5:在web項目中controller中的大概寫法,這樣前端直接調用這個方法,就會在頁面上直接下載了
//**********************************開始****************************************
public String exportWord(HttpServletRequest request, HttpServletResponse response) {
List<Map<String,Object>> dataList = DjOrgTxlDwryServiceImpl.exportWord();//獲取數據,通常是從庫裏查詢的數據,這裏能夠改爲本身造的數據
if(!ObjectUtils.isEmpty(dataList)){//判斷數據不爲null,而且不爲空
try {
XWPFDocument document= WordExport.initDoc(dataList);
String filename="部門通信錄";
response.setHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes(), "iso8859-1")+".docx");
OutputStream out = response.getOutputStream();
document.write(out);
out.close();
return null;
} catch (IOException e) {
return "導出數據異常!!!!!";
}
}else{
return "查詢數據爲空,沒有要導出的數據";
}
}
//**********************************結束***************************************
6:在web項目中獲取項目中圖片的寫法
//========插入圖片===============
XWPFParagraph pictures = document.createParagraph();
pictures.setIndentationLeft(300);//前面縮進300
XWPFRun insertNewRun = pictures.createRun();
int format =XWPFDocument.PICTURE_TYPE_PNG;
try {
ClassPathResource classPathResource = new ClassPathResource("image/123.png");
InputStream instream = classPathResource.getInputStream();
String imgFile = classPathResource.getPath();
insertNewRun.addPicture(instream, format, imgFile, Units.toEMU(250), Units.toEMU(45)); // 200x200 pixels
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) { e.printStackTrace();}