poi导出word表格详解 超详细了

时间:2022-04-06 05:36:14

转:非常感谢原作者

2018年07月20日 10:41:33 Z丶royAl 阅读数:36138

一、效果如下

poi导出word表格详解 超详细了

二、js代码

function export_word(){ //导出word
var url = "czzsca/exportWord.do";
this.export(url);
}
function export(url){
var currentyear = $("#mainYear").val() * 1;
var key_columns = ['xh',"d_name","d_unit","d_number","d_estimate","d_lastyear","jnjh","d_remarks","d_depart","d_executeunit"];
var value_columns = ['序号','项目名称','单位','数量','总概算','至'+(currentyear-1)+'年完成',currentyear+'年计划','附注','责任部门','计划执行单位'];
window.location.href= url+"?key_columns="+key_columns+"&value_columns="+value_columns+"&title="+currentyear+"年 更新改造计划 正式计划草案";
}

三、controller代码(controller代码比较长,主要是格式化每一行的数据,主要是往工具类里传List<List<String>>参数,泛型的List<String>是每一行,String是每一列)

    //导出word
@RequestMapping("/exportWord.do")
@ResponseBody
public ReturnMsg exportWord(String[] key_columns,String[] value_columns,String title,HttpServletResponse response){
ReturnMsg rm = new ReturnMsg();
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/msexcle");
response.setHeader("content-disposition", "attachment;filename="+new String("正式计划草案".getBytes("gb2312"),"ISO8859-1")+".doc");
List<List<String>> content = new ArrayList<List<String>>();
List<List<String>> head = new ArrayList<List<String>>();
String jnjhzh = new BigDecimal(this.map.get("jnjhzh")==null||"".equals(this.map.get("jnjhzh")+"")?"0":this.map.get("jnjhzh")+"").setScale(1, RoundingMode.UP)+"";
String trimpro = new BigDecimal(this.map.get("tzjh")==null||"".equals(this.map.get("tzjh")+"")?"0":this.map.get("tzjh")+"").setScale(1, RoundingMode.UP)+"";
String temp = new BigDecimal(trimpro).subtract(new BigDecimal(jnjhzh))+"";
if("0".equals(temp)) {
temp = "";
}
head = ExportUtil.getCzzscaList(jnjhzh, trimpro, temp);
Map dounit = new HashMap();
dounit.put("dwlx", 0);
dounit.put("user_type", 1);
List<Map> d_executeunit = unitDao.selectByPrimaryKey(dounit);
Map zrbm = new HashMap();
zrbm.put("dwlx", 1);
zrbm.put("user_type", 1);
List<Map> d_zrbm = unitDao.selectByPrimaryKey(zrbm);
List<Map> zmtype = nd_caController.findProType("2-3-4");
for (Map map: this.list) {
List<String> row = new ArrayList<String>();
for (int i = 0; i < key_columns.length; i++) {
System.out.print(map.get(key_columns[i])+",");
Object Otzjh = map.get("tzjh")!=null?map.get("tzjh"):0;
Object Ojnjh = map.get("jnjh")!=null?map.get("jnjh"):0;
BigDecimal tzjh = null;
BigDecimal jnjh = null;
if ("tzjh".equals(key_columns[i])||"jnjh".equals(key_columns[i])||"d_lnorde".equals(key_columns[i])) {
if(Otzjh instanceof BigDecimal) {
tzjh = (BigDecimal)Otzjh;
}else {
tzjh = new BigDecimal(Otzjh+"");
}
if(Ojnjh instanceof BigDecimal) {
jnjh = (BigDecimal)Ojnjh;
}else {
jnjh = new BigDecimal(Ojnjh+"");
} }
if ("d_lnorde".equals(key_columns[i])) {
if(map.get("flag")!=null&&"2".equals((map.get("flag")+""))) {
row.add("");
}else {
row.add(tzjh.subtract(jnjh).setScale(1, RoundingMode.UP)+""); //不为整数则四舍五入
}
}else if ("xh".equals(key_columns[i])&&map.get("xh")!=null) {
if(map.get("xh").toString().indexOf("、")>-1) {
row.add(map.get("xh").toString().replace("、", "").trim());
}else {
row.add(map.get("xh")+""); //不为整数则四舍五入
}
}else if("tzjh".equals(key_columns[i])&&map.get("tzjh")!=null) {
if(ExportUtil.isNumeric(tzjh+"")) { //判断相减是否为整数
row.add(tzjh+"");
}else {
String stzjh = tzjh.setScale(1, RoundingMode.UP)+"";
row.add("0".equals(stzjh.charAt(stzjh.indexOf(".")+1)+"")?stzjh.replace(".0", ""):stzjh);//不为整数则四舍五入
}
}else if("d_estimate".equals(key_columns[i])&&map.get("d_estimate")!=null) {
if("0".equals(map.get("d_estimate")+"")) {
row.add("");
}else {
row.add(map.get("d_estimate")+"");
}
}else if("d_number".equals(key_columns[i])&&map.get("d_number")!=null) {
if("0".equals(map.get("d_number")+"")) {
row.add("");
}else {
row.add(map.get("d_number")+"");
}
}else if("jnjh".equals(key_columns[i])&&map.get("jnjh")!=null) {
if(ExportUtil.isNumeric(jnjh+"")) { //判断相减是否为整数
row.add(jnjh+"");
}else {
String sjnjh = jnjh.setScale(1, RoundingMode.UP)+"";
row.add("0".equals(sjnjh.charAt(sjnjh.indexOf(".")+1)+"")?sjnjh.replace(".0", ""):sjnjh); //不为整数则四舍五入
}
}else if("d_pro_type".equals(key_columns[i])&&map.get("d_pro_type")!=null) {
for (Map m : zmtype) {
if((map.get("d_pro_type")+"").equals(m.get("TYPE_ID")+"")){
row.add(m.get("NUM")+"");
break;
}
}
}else if("d_depart".equals(key_columns[i])&&map.get("d_depart")!=null) {
String d_depart = map.get("d_depart")+"";
String depart = "";
for (Map m : d_zrbm) {
if((d_depart).indexOf(",")>-1) {
for (String string : d_depart.split(",")) {
if((string).equals(m.get("ID")+"")) {
depart += ","+m.get("UNITNAME")+"";
break;
}
}
}else {
if((d_depart).equals(m.get("ID")+"")) {
depart = ","+m.get("UNITNAME")+"";
break;
}
}
}
if (StringUtils.isNotBlank(depart)) {
depart = depart.substring(1, depart.length()).replace(",", "\r ");
row.add(depart);
}else {
row.add("");
}
}else if("d_executeunit".equals(key_columns[i])&&map.get("d_executeunit")!=null) {
boolean flag;
for (Map m : d_executeunit) {
flag = false;
String executeunit = map.get("d_executeunit")+"";
if((executeunit).indexOf(",")>-1) {
for (String string : executeunit.split(",")) {
if((string).equals(m.get("ID")+"")) {
row.add((m.get("UNITNAME")+"").trim());
flag = true;
break;
}
}
if (flag) {
break;
} }else {
if((executeunit).equals(m.get("ID")+"")) {
row.add((m.get("UNITNAME")+"").trim());
break;
}
}
}
}else {
if(map.get(key_columns[i])==null) {
row.add("");
}else {
row.add((map.get(key_columns[i])+"").trim());
}
}
}
content.add(row);
}
head.addAll(content);
int[] colWidths = new int[] { 600, 3000, 500, 500, 800, 800 ,800,3000,800,1500};
XWPFDocument document = ExportUtil.exportWord(title,value_columns, head,colWidths,1,7);
OutputStream out = response.getOutputStream();
document.write(out);
out.close();
rm.setCode("1");
rm.setMsg("导出成功");
} catch (Exception e) {
e.printStackTrace();
rm.setCode("0");
rm.setMsg("导出失败,请刷新重试。");
}
return rm;
}

四、工具类代码

    /**
*
* @Date 2018年7月19日 上午11:19:04
* @Description 导出word
* @Fcunction exportWord
* @param title
* @param value_columns
* @param list
* @return XWPFDocument
*
*/
public static XWPFDocument exportWord(String title,String[] value_columns, List<List<String>> list,int[] colWidths,int one,int two) {
XWPFDocument doc= new XWPFDocument(); CTDocument1 document = doc.getDocument();
CTBody body = document.getBody();
if(!body.isSetSectPr()){
body.addNewSectPr();
}
CTSectPr section = body.getSectPr(); if(!section.isSetPgSz()){
section.addNewPgSz();
}
CTPageSz pageSize = section.getPgSz();
pageSize.setW(BigInteger.valueOf(15840));
pageSize.setH(BigInteger.valueOf(12240));
pageSize.setOrient(STPageOrientation.LANDSCAPE); //添加标题
XWPFParagraph titleParagraph = doc.createParagraph(); //设置段落居中
titleParagraph.setAlignment(ParagraphAlignment.CENTER); XWPFRun titleParagraphRun = titleParagraph.createRun();
titleParagraphRun.setText(title);
titleParagraphRun.setColor("000000");
titleParagraphRun.setFontSize(20); //表格
XWPFTable ComTable = doc.createTable(); //设置指定宽度
CTTbl ttbl = ComTable.getCTTbl();
CTTblGrid tblGrid = ttbl.addNewTblGrid();
for (int i : colWidths) {
CTTblGridCol gridCol = tblGrid.addNewGridCol();
gridCol.setW(new BigInteger(i+""));
} //表头
XWPFTableRow rowHead = ComTable.getRow(0);
XWPFParagraph cellParagraph = rowHead.getCell(0).getParagraphs().get(0);
cellParagraph.setAlignment(ParagraphAlignment.CENTER); //设置表头单元格居中
XWPFRun cellParagraphRun = cellParagraph.createRun();
cellParagraphRun.setFontSize(10); //设置表头单元格字号
cellParagraphRun.setBold(true); //设置表头单元格加粗
cellParagraphRun.setText(value_columns[0]);
for (int i = 1; i < value_columns.length; i++) {
if(value_columns[i].indexOf("增减")>-1) {
cellParagraph = rowHead.addNewTableCell().getParagraphs().get(0);
cellParagraph.setAlignment(ParagraphAlignment.CENTER); //设置表头单元格居中
cellParagraphRun = cellParagraph.createRun();
cellParagraphRun.setFontSize(10); //设置表头单元格居中
cellParagraphRun.setBold(true);
cellParagraphRun.setText("增减(+ / -)");
}else {
cellParagraph = rowHead.addNewTableCell().getParagraphs().get(0);
cellParagraph.setAlignment(ParagraphAlignment.CENTER); //设置表头单元格居中
cellParagraphRun = cellParagraph.createRun();
cellParagraphRun.setFontSize(10); //设置表头单元格居中
cellParagraphRun.setBold(true); //设置表头单元格加粗
cellParagraphRun.setText(value_columns[i]);
}
}
int rows = list.size();
//表格内容
for (int i = 0; i < rows; i++) {
XWPFTableRow rowsContent = ComTable.createRow();
for (int j = 0; j < list.get(i).size(); j++) {
XWPFParagraph cellParagraphC = rowsContent.getCell(j).getParagraphs().get(0);
if(j!=one&&j!=two) {
cellParagraphC.setAlignment(ParagraphAlignment.CENTER); //设置表格内容居中
}
XWPFRun cellParagraphRunC = cellParagraphC.createRun();
cellParagraphRunC.setFontSize(10); //设置表格内容字号
cellParagraphRunC.setText(list.get(i).get(j)+""); //单元格段落加载内容
}
}
if(rows==0) {
for (int i = 0; i < value_columns.length; i++) {
XWPFTableCell cell = ComTable.getRow(0).getCell(i);
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
}
}else {
//设置居中
for (int i = 0; i <= rows; i++) {
for (int j = 0; j < list.get(0).size(); j++) {
XWPFTableCell cell = ComTable.getRow(i).getCell(j);
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
}
}
}
return doc;
} /**
*
* @Date 2018年7月19日 上午11:19:21
* @Description 判断是否是整数
* @Fcunction isNumeric
* @param str
* @return boolean
*
*/
public static boolean isNumeric(String str) {
if(str.indexOf(".")>0) {
return false;
}
return true;
} /**
*
* @Date 2018年7月19日 上午11:44:48
* @Description 正式计划草案获取前两行
* @Fcunction getCzzscaList
* @param jnjhzh
* @param trimpro
* @param temp
* @return List<List<String>>
*
*/
public static List<List<String>> getCzzscaList(String jnjhzh,String trimpro,String temp) {
List<List<String>> list = new ArrayList<List<String>>();
List<String> l1 = new ArrayList<String>(); //固定第一行
l1.add("");
l1.add("年度总计");
l1.add("");
l1.add("");
l1.add("");
l1.add("");
l1.add(jnjhzh);
l1.add("");
l1.add("");
l1.add("");
list.add(l1);
List<String> l2 = new ArrayList<String>(); //固定第二行
l2.add("");
l2.add("搜索总计");
l2.add("");
l2.add("");
l2.add("");
l2.add("");
l2.add("");
// l2.add(trimpro+"\r100%");
l2.add("");
l2.add("");
l2.add("");
list.add(l2);
return list;
}

五、详解:

1.设置纸张大小

(1)创建完XWPFDocument后,默认为A4纸张,如需调整纸张大小,这里我是要用A3大小使用如下代码

XWPFDocument doc= new XWPFDocument();
CTDocument1 document = doc.getDocument();
CTBody body = document.getBody();
if(!body.isSetSectPr()){
body.addNewSectPr();
}
CTSectPr section = body.getSectPr(); if(!section.isSetPgSz()){
section.addNewPgSz();
}
CTPageSz pageSize = section.getPgSz();
pageSize.setW(BigInteger.valueOf(15840));
pageSize.setH(BigInteger.valueOf(12240));
pageSize.setOrient(STPageOrientation.LANDSCAPE);

(2)默认A4纸张大小的话只用XWPFDocument

XWPFDocument doc= new XWPFDocument();

(3)使用CTPageSz类需要导入ooxml-schemas的jar包(所有需要的jar包maven依赖在底部)

2.单元格列宽度

(1)每一列宽度相等自适应,不需单独设置每一列宽度的话使用如下代码

//表格
XWPFTable ComTable = doc.createTable();
//表格自适应宽度
CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
comTableWidth.setType(STTblWidth.DXA);
comTableWidth.setW(BigInteger.valueOf(9072));

(2)单独设置每列宽度

//表格
XWPFTable ComTable = doc.createTable();
//设置指定宽度
CTTbl ttbl = ComTable.getCTTbl();
CTTblGrid tblGrid = ttbl.addNewTblGrid();
int[] colWidths = new int[] { 600, 3000, 500, 500, 800, 800 ,800,3000,800,1500};
for (int i : colWidths) {
CTTblGridCol gridCol = tblGrid.addNewGridCol();
gridCol.setW(new BigInteger(i+""));
}

(3)使用CTTblGrid类需要导入poi-ooxml-schemas的jar包(所有需要的jar包maven依赖在底部)

3.单元格内字体样式

(1)不需要设置单元格字体

for (int i = 0; i < rows; i++) {
XWPFTableRow rowsContent = ComTable.createRow();
for (int j = 0; j < list.get(i).size(); j++) {
rowsContent.getCell(j).setText(list.get(i).get(j)+""); //用单元格加载内容
}
}

(2)设置单元格内字体字号、是否加粗

for (int i = 0; i < rows; i++) {
XWPFTableRow rowsContent = ComTable.createRow();
for (int j = 0; j < list.get(i).size(); j++) {
XWPFParagraph cellParagraphC = rowsContent.getCell(j).getParagraphs().get(0);
if(j!=1&&j!=7) {
cellParagraphC.setAlignment(ParagraphAlignment.CENTER); //设置表格内容居中
}
XWPFRun cellParagraphRunC = cellParagraphC.createRun();
cellParagraphRunC.setFontSize(10); //设置表格内容字号
cellParagraphRun.setBold(true); //设置表头单元格加粗
cellParagraphRunC.setText(list.get(i).get(j)+""); //单元格段落加载内容
}
}

4.单元格居中(水平居中、垂直居中)

(1)使用单元格加载内容

for (int i = 0; i < value_columns.length; i++) {
XWPFTableCell cell = ComTable.getRow(0).getCell(i);
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
CTTc cttc = cell.getCTTc();
CTP ctp = cttc.getPList().get(0);
CTPPr ctppr = ctp.getPPr();
if (ctppr == null) {
ctppr = ctp.addNewPPr();
}
CTJc ctjc = ctppr.getJc();
if (ctjc == null) {
ctjc = ctppr.addNewJc();
}
ctjc.setVal(STJc.CENTER); //水平居中
}

(2)使用单元格的段落加载内容,只用调用垂直居中的方法

for (int i = 0; i < value_columns.length; i++) {
XWPFTableCell cell = ComTable.getRow(0).getCell(i);
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
}

水平居中在3-(2)里调用了段落的方法居中过了

cellParagraphC.setAlignment(ParagraphAlignment.CENTER);

5.单元格合并

(1)跨列合并单元格

public static void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
if ( cellIndex == fromCell ) {
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
} else {
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
}
}
}

(2)跨行合并单元格

public static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
if ( rowIndex == fromRow ) {
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
} else {
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
}
}
}

六、使用到的Maven依赖

<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.16</version>
</dependency>

poi导出word表格详解

2018年07月20日 10:41:33 Z丶royAl 阅读数:36138

一、效果如下

poi导出word表格详解 超详细了

二、js代码

  1. function export_word(){ //导出word
  2. var url = "czzsca/exportWord.do";
  3. this.export(url);
  4. }
  5. function export(url){
  6. var currentyear = $("#mainYear").val() * 1;
  7. var key_columns = ['xh',"d_name","d_unit","d_number","d_estimate","d_lastyear","jnjh","d_remarks","d_depart","d_executeunit"];
  8. var value_columns = ['序号','项目名称','单位','数量','总概算','至'+(currentyear-1)+'年完成',currentyear+'年计划','附注','责任部门','计划执行单位'];
  9. window.location.href= url+"?key_columns="+key_columns+"&value_columns="+value_columns+"&title="+currentyear+"年 更新改造计划 正式计划草案";
  10. }

三、controller代码(controller代码比较长,主要是格式化每一行的数据,主要是往工具类里传List<List<String>>参数,泛型的List<String>是每一行,String是每一列)

  1. //导出word
  2. @RequestMapping("/exportWord.do")
  3. @ResponseBody
  4. public ReturnMsg exportWord(String[] key_columns,String[] value_columns,String title,HttpServletResponse response){
  5. ReturnMsg rm = new ReturnMsg();
  6. try {
  7. response.setCharacterEncoding("UTF-8");
  8. response.setContentType("application/msexcle");
  9. response.setHeader("content-disposition", "attachment;filename="+new String("正式计划草案".getBytes("gb2312"),"ISO8859-1")+".doc");
  10. List<List<String>> content = new ArrayList<List<String>>();
  11. List<List<String>> head = new ArrayList<List<String>>();
  12. String jnjhzh = new BigDecimal(this.map.get("jnjhzh")==null||"".equals(this.map.get("jnjhzh")+"")?"0":this.map.get("jnjhzh")+"").setScale(1, RoundingMode.UP)+"";
  13. String trimpro = new BigDecimal(this.map.get("tzjh")==null||"".equals(this.map.get("tzjh")+"")?"0":this.map.get("tzjh")+"").setScale(1, RoundingMode.UP)+"";
  14. String temp = new BigDecimal(trimpro).subtract(new BigDecimal(jnjhzh))+"";
  15. if("0".equals(temp)) {
  16. temp = "";
  17. }
  18. head = ExportUtil.getCzzscaList(jnjhzh, trimpro, temp);
  19. Map dounit = new HashMap();
  20. dounit.put("dwlx", 0);
  21. dounit.put("user_type", 1);
  22. List<Map> d_executeunit = unitDao.selectByPrimaryKey(dounit);
  23. Map zrbm = new HashMap();
  24. zrbm.put("dwlx", 1);
  25. zrbm.put("user_type", 1);
  26. List<Map> d_zrbm = unitDao.selectByPrimaryKey(zrbm);
  27. List<Map> zmtype = nd_caController.findProType("2-3-4");
  28. for (Map map: this.list) {
  29. List<String> row = new ArrayList<String>();
  30. for (int i = 0; i < key_columns.length; i++) {
  31. System.out.print(map.get(key_columns[i])+",");
  32. Object Otzjh = map.get("tzjh")!=null?map.get("tzjh"):0;
  33. Object Ojnjh = map.get("jnjh")!=null?map.get("jnjh"):0;
  34. BigDecimal tzjh = null;
  35. BigDecimal jnjh = null;
  36. if ("tzjh".equals(key_columns[i])||"jnjh".equals(key_columns[i])||"d_lnorde".equals(key_columns[i])) {
  37. if(Otzjh instanceof BigDecimal) {
  38. tzjh = (BigDecimal)Otzjh;
  39. }else {
  40. tzjh = new BigDecimal(Otzjh+"");
  41. }
  42. if(Ojnjh instanceof BigDecimal) {
  43. jnjh = (BigDecimal)Ojnjh;
  44. }else {
  45. jnjh = new BigDecimal(Ojnjh+"");
  46. }
  47. }
  48. if ("d_lnorde".equals(key_columns[i])) {
  49. if(map.get("flag")!=null&&"2".equals((map.get("flag")+""))) {
  50. row.add("");
  51. }else {
  52. row.add(tzjh.subtract(jnjh).setScale(1, RoundingMode.UP)+""); //不为整数则四舍五入
  53. }
  54. }else if ("xh".equals(key_columns[i])&&map.get("xh")!=null) {
  55. if(map.get("xh").toString().indexOf("、")>-1) {
  56. row.add(map.get("xh").toString().replace("、", "").trim());
  57. }else {
  58. row.add(map.get("xh")+""); //不为整数则四舍五入
  59. }
  60. }else if("tzjh".equals(key_columns[i])&&map.get("tzjh")!=null) {
  61. if(ExportUtil.isNumeric(tzjh+"")) { //判断相减是否为整数
  62. row.add(tzjh+"");
  63. }else {
  64. String stzjh = tzjh.setScale(1, RoundingMode.UP)+"";
  65. row.add("0".equals(stzjh.charAt(stzjh.indexOf(".")+1)+"")?stzjh.replace(".0", ""):stzjh);//不为整数则四舍五入
  66. }
  67. }else if("d_estimate".equals(key_columns[i])&&map.get("d_estimate")!=null) {
  68. if("0".equals(map.get("d_estimate")+"")) {
  69. row.add("");
  70. }else {
  71. row.add(map.get("d_estimate")+"");
  72. }
  73. }else if("d_number".equals(key_columns[i])&&map.get("d_number")!=null) {
  74. if("0".equals(map.get("d_number")+"")) {
  75. row.add("");
  76. }else {
  77. row.add(map.get("d_number")+"");
  78. }
  79. }else if("jnjh".equals(key_columns[i])&&map.get("jnjh")!=null) {
  80. if(ExportUtil.isNumeric(jnjh+"")) { //判断相减是否为整数
  81. row.add(jnjh+"");
  82. }else {
  83. String sjnjh = jnjh.setScale(1, RoundingMode.UP)+"";
  84. row.add("0".equals(sjnjh.charAt(sjnjh.indexOf(".")+1)+"")?sjnjh.replace(".0", ""):sjnjh); //不为整数则四舍五入
  85. }
  86. }else if("d_pro_type".equals(key_columns[i])&&map.get("d_pro_type")!=null) {
  87. for (Map m : zmtype) {
  88. if((map.get("d_pro_type")+"").equals(m.get("TYPE_ID")+"")){
  89. row.add(m.get("NUM")+"");
  90. break;
  91. }
  92. }
  93. }else if("d_depart".equals(key_columns[i])&&map.get("d_depart")!=null) {
  94. String d_depart = map.get("d_depart")+"";
  95. String depart = "";
  96. for (Map m : d_zrbm) {
  97. if((d_depart).indexOf(",")>-1) {
  98. for (String string : d_depart.split(",")) {
  99. if((string).equals(m.get("ID")+"")) {
  100. depart += ","+m.get("UNITNAME")+"";
  101. break;
  102. }
  103. }
  104. }else {
  105. if((d_depart).equals(m.get("ID")+"")) {
  106. depart = ","+m.get("UNITNAME")+"";
  107. break;
  108. }
  109. }
  110. }
  111. if (StringUtils.isNotBlank(depart)) {
  112. depart = depart.substring(1, depart.length()).replace(",", "\r ");
  113. row.add(depart);
  114. }else {
  115. row.add("");
  116. }
  117. }else if("d_executeunit".equals(key_columns[i])&&map.get("d_executeunit")!=null) {
  118. boolean flag;
  119. for (Map m : d_executeunit) {
  120. flag = false;
  121. String executeunit = map.get("d_executeunit")+"";
  122. if((executeunit).indexOf(",")>-1) {
  123. for (String string : executeunit.split(",")) {
  124. if((string).equals(m.get("ID")+"")) {
  125. row.add((m.get("UNITNAME")+"").trim());
  126. flag = true;
  127. break;
  128. }
  129. }
  130. if (flag) {
  131. break;
  132. }
  133. }else {
  134. if((executeunit).equals(m.get("ID")+"")) {
  135. row.add((m.get("UNITNAME")+"").trim());
  136. break;
  137. }
  138. }
  139. }
  140. }else {
  141. if(map.get(key_columns[i])==null) {
  142. row.add("");
  143. }else {
  144. row.add((map.get(key_columns[i])+"").trim());
  145. }
  146. }
  147. }
  148. content.add(row);
  149. }
  150. head.addAll(content);
  151. int[] colWidths = new int[] { 600, 3000, 500, 500, 800, 800 ,800,3000,800,1500};
  152. XWPFDocument document = ExportUtil.exportWord(title,value_columns, head,colWidths,1,7);
  153. OutputStream out = response.getOutputStream();
  154. document.write(out);
  155. out.close();
  156. rm.setCode("1");
  157. rm.setMsg("导出成功");
  158. } catch (Exception e) {
  159. e.printStackTrace();
  160. rm.setCode("0");
  161. rm.setMsg("导出失败,请刷新重试。");
  162. }
  163. return rm;
  164. }

四、工具类代码

  1. /**
  2. *
  3. * @Date 2018年7月19日 上午11:19:04
  4. * @Description 导出word
  5. * @Fcunction exportWord
  6. * @param title
  7. * @param value_columns
  8. * @param list
  9. * @return XWPFDocument
  10. *
  11. */
  12. public static XWPFDocument exportWord(String title,String[] value_columns, List<List<String>> list,int[] colWidths,int one,int two) {
  13. XWPFDocument doc= new XWPFDocument();
  14. CTDocument1 document = doc.getDocument();
  15. CTBody body = document.getBody();
  16. if(!body.isSetSectPr()){
  17. body.addNewSectPr();
  18. }
  19. CTSectPr section = body.getSectPr();
  20. if(!section.isSetPgSz()){
  21. section.addNewPgSz();
  22. }
  23. CTPageSz pageSize = section.getPgSz();
  24. pageSize.setW(BigInteger.valueOf(15840));
  25. pageSize.setH(BigInteger.valueOf(12240));
  26. pageSize.setOrient(STPageOrientation.LANDSCAPE);
  27. //添加标题
  28. XWPFParagraph titleParagraph = doc.createParagraph();
  29. //设置段落居中
  30. titleParagraph.setAlignment(ParagraphAlignment.CENTER);
  31. XWPFRun titleParagraphRun = titleParagraph.createRun();
  32. titleParagraphRun.setText(title);
  33. titleParagraphRun.setColor("000000");
  34. titleParagraphRun.setFontSize(20);
  35. //表格
  36. XWPFTable ComTable = doc.createTable();
  37. //设置指定宽度
  38. CTTbl ttbl = ComTable.getCTTbl();
  39. CTTblGrid tblGrid = ttbl.addNewTblGrid();
  40. for (int i : colWidths) {
  41. CTTblGridCol gridCol = tblGrid.addNewGridCol();
  42. gridCol.setW(new BigInteger(i+""));
  43. }
  44. //表头
  45. XWPFTableRow rowHead = ComTable.getRow(0);
  46. XWPFParagraph cellParagraph = rowHead.getCell(0).getParagraphs().get(0);
  47. cellParagraph.setAlignment(ParagraphAlignment.CENTER); //设置表头单元格居中
  48. XWPFRun cellParagraphRun = cellParagraph.createRun();
  49. cellParagraphRun.setFontSize(10); //设置表头单元格字号
  50. cellParagraphRun.setBold(true); //设置表头单元格加粗
  51. cellParagraphRun.setText(value_columns[0]);
  52. for (int i = 1; i < value_columns.length; i++) {
  53. if(value_columns[i].indexOf("增减")>-1) {
  54. cellParagraph = rowHead.addNewTableCell().getParagraphs().get(0);
  55. cellParagraph.setAlignment(ParagraphAlignment.CENTER); //设置表头单元格居中
  56. cellParagraphRun = cellParagraph.createRun();
  57. cellParagraphRun.setFontSize(10); //设置表头单元格居中
  58. cellParagraphRun.setBold(true);
  59. cellParagraphRun.setText("增减(+ / -)");
  60. }else {
  61. cellParagraph = rowHead.addNewTableCell().getParagraphs().get(0);
  62. cellParagraph.setAlignment(ParagraphAlignment.CENTER); //设置表头单元格居中
  63. cellParagraphRun = cellParagraph.createRun();
  64. cellParagraphRun.setFontSize(10); //设置表头单元格居中
  65. cellParagraphRun.setBold(true); //设置表头单元格加粗
  66. cellParagraphRun.setText(value_columns[i]);
  67. }
  68. }
  69. int rows = list.size();
  70. //表格内容
  71. for (int i = 0; i < rows; i++) {
  72. XWPFTableRow rowsContent = ComTable.createRow();
  73. for (int j = 0; j < list.get(i).size(); j++) {
  74. XWPFParagraph cellParagraphC = rowsContent.getCell(j).getParagraphs().get(0);
  75. if(j!=one&&j!=two) {
  76. cellParagraphC.setAlignment(ParagraphAlignment.CENTER); //设置表格内容居中
  77. }
  78. XWPFRun cellParagraphRunC = cellParagraphC.createRun();
  79. cellParagraphRunC.setFontSize(10); //设置表格内容字号
  80. cellParagraphRunC.setText(list.get(i).get(j)+""); //单元格段落加载内容
  81. }
  82. }
  83. if(rows==0) {
  84. for (int i = 0; i < value_columns.length; i++) {
  85. XWPFTableCell cell = ComTable.getRow(0).getCell(i);
  86. cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
  87. }
  88. }else {
  89. //设置居中
  90. for (int i = 0; i <= rows; i++) {
  91. for (int j = 0; j < list.get(0).size(); j++) {
  92. XWPFTableCell cell = ComTable.getRow(i).getCell(j);
  93. cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
  94. }
  95. }
  96. }
  97. return doc;
  98. }
  99. /**
  100. *
  101. * @Date 2018年7月19日 上午11:19:21
  102. * @Description 判断是否是整数
  103. * @Fcunction isNumeric
  104. * @param str
  105. * @return boolean
  106. *
  107. */
  108. public static boolean isNumeric(String str) {
  109. if(str.indexOf(".")>0) {
  110. return false;
  111. }
  112. return true;
  113. }
  114. /**
  115. *
  116. * @Date 2018年7月19日 上午11:44:48
  117. * @Description 正式计划草案获取前两行
  118. * @Fcunction getCzzscaList
  119. * @param jnjhzh
  120. * @param trimpro
  121. * @param temp
  122. * @return List<List<String>>
  123. *
  124. */
  125. public static List<List<String>> getCzzscaList(String jnjhzh,String trimpro,String temp) {
  126. List<List<String>> list = new ArrayList<List<String>>();
  127. List<String> l1 = new ArrayList<String>(); //固定第一行
  128. l1.add("");
  129. l1.add("年度总计");
  130. l1.add("");
  131. l1.add("");
  132. l1.add("");
  133. l1.add("");
  134. l1.add(jnjhzh);
  135. l1.add("");
  136. l1.add("");
  137. l1.add("");
  138. list.add(l1);
  139. List<String> l2 = new ArrayList<String>(); //固定第二行
  140. l2.add("");
  141. l2.add("搜索总计");
  142. l2.add("");
  143. l2.add("");
  144. l2.add("");
  145. l2.add("");
  146. l2.add("");
  147. // l2.add(trimpro+"\r100%");
  148. l2.add("");
  149. l2.add("");
  150. l2.add("");
  151. list.add(l2);
  152. return list;
  153. }

五、详解:

1.设置纸张大小

(1)创建完XWPFDocument后,默认为A4纸张,如需调整纸张大小,这里我是要用A3大小使用如下代码

  1. XWPFDocument doc= new XWPFDocument();
  2. CTDocument1 document = doc.getDocument();
  3. CTBody body = document.getBody();
  4. if(!body.isSetSectPr()){
  5. body.addNewSectPr();
  6. }
  7. CTSectPr section = body.getSectPr();
  8. if(!section.isSetPgSz()){
  9. section.addNewPgSz();
  10. }
  11. CTPageSz pageSize = section.getPgSz();
  12. pageSize.setW(BigInteger.valueOf(15840));
  13. pageSize.setH(BigInteger.valueOf(12240));
  14. pageSize.setOrient(STPageOrientation.LANDSCAPE);

(2)默认A4纸张大小的话只用XWPFDocument

XWPFDocument doc= new XWPFDocument();

(3)使用CTPageSz类需要导入ooxml-schemas的jar包(所有需要的jar包maven依赖在底部)

2.单元格列宽度

(1)每一列宽度相等自适应,不需单独设置每一列宽度的话使用如下代码

  1. //表格
  2. XWPFTable ComTable = doc.createTable();
  3. //表格自适应宽度
  4. CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
  5. comTableWidth.setType(STTblWidth.DXA);
  6. comTableWidth.setW(BigInteger.valueOf(9072));

(2)单独设置每列宽度

  1. //表格
  2. XWPFTable ComTable = doc.createTable();
  3. //设置指定宽度
  4. CTTbl ttbl = ComTable.getCTTbl();
  5. CTTblGrid tblGrid = ttbl.addNewTblGrid();
  6. int[] colWidths = new int[] { 600, 3000, 500, 500, 800, 800 ,800,3000,800,1500};
  7. for (int i : colWidths) {
  8. CTTblGridCol gridCol = tblGrid.addNewGridCol();
  9. gridCol.setW(new BigInteger(i+""));
  10. }

(3)使用CTTblGrid类需要导入poi-ooxml-schemas的jar包(所有需要的jar包maven依赖在底部)

3.单元格内字体样式

(1)不需要设置单元格字体

  1. for (int i = 0; i < rows; i++) {
  2. XWPFTableRow rowsContent = ComTable.createRow();
  3. for (int j = 0; j < list.get(i).size(); j++) {
  4. rowsContent.getCell(j).setText(list.get(i).get(j)+""); //用单元格加载内容
  5. }
  6. }

(2)设置单元格内字体字号、是否加粗

  1. for (int i = 0; i < rows; i++) {
  2. XWPFTableRow rowsContent = ComTable.createRow();
  3. for (int j = 0; j < list.get(i).size(); j++) {
  4. XWPFParagraph cellParagraphC = rowsContent.getCell(j).getParagraphs().get(0);
  5. if(j!=1&&j!=7) {
  6. cellParagraphC.setAlignment(ParagraphAlignment.CENTER); //设置表格内容居中
  7. }
  8. XWPFRun cellParagraphRunC = cellParagraphC.createRun();
  9. cellParagraphRunC.setFontSize(10); //设置表格内容字号
  10. cellParagraphRun.setBold(true); //设置表头单元格加粗
  11. cellParagraphRunC.setText(list.get(i).get(j)+""); //单元格段落加载内容
  12. }
  13. }

4.单元格居中(水平居中、垂直居中)

(1)使用单元格加载内容

  1. for (int i = 0; i < value_columns.length; i++) {
  2. XWPFTableCell cell = ComTable.getRow(0).getCell(i);
  3. cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
  4. CTTc cttc = cell.getCTTc();
  5. CTP ctp = cttc.getPList().get(0);
  6. CTPPr ctppr = ctp.getPPr();
  7. if (ctppr == null) {
  8. ctppr = ctp.addNewPPr();
  9. }
  10. CTJc ctjc = ctppr.getJc();
  11. if (ctjc == null) {
  12. ctjc = ctppr.addNewJc();
  13. }
  14. ctjc.setVal(STJc.CENTER); //水平居中
  15. }

(2)使用单元格的段落加载内容,只用调用垂直居中的方法

  1. for (int i = 0; i < value_columns.length; i++) {
  2. XWPFTableCell cell = ComTable.getRow(0).getCell(i);
  3. cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
  4. }

水平居中在3-(2)里调用了段落的方法居中过了

cellParagraphC.setAlignment(ParagraphAlignment.CENTER);

5.单元格合并

(1)跨列合并单元格

  1. public static void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
  2. for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
  3. XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
  4. if ( cellIndex == fromCell ) {
  5. cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
  6. } else {
  7. cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
  8. }
  9. }
  10. }

(2)跨行合并单元格

  1. public static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
  2. for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
  3. XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
  4. if ( rowIndex == fromRow ) {
  5. cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
  6. } else {
  7. cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
  8. }
  9. }
  10. }

六、使用到的Maven依赖

  1. <dependency>
  2. <groupId>org.apache.xmlbeans</groupId>
  3. <artifactId>xmlbeans</artifactId>
  4. <version>2.6.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi-ooxml</artifactId>
  9. <version>3.9</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.poi</groupId>
  13. <artifactId>ooxml-schemas</artifactId>
  14. <version>1.1</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.apache.poi</groupId>
  18. <artifactId>poi-ooxml-schemas</artifactId>
  19. <version>3.16</version>
  20. </dependency>