首页 > 其他分享 >生成word文档,内容为表格(第一次实操)

生成word文档,内容为表格(第一次实操)

时间:2024-07-04 14:10:12浏览次数:18  
标签:word import setText getRow 文档 实操 getCell table setWidth

package com.cqbb.common.utils.poi;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cqbb.common.config.BBKJConfig;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;

import java.io.*;
import java.math.BigInteger;
import java.util.Base64;
/**
* 我这里是循环调用的,所以在上一级创建的 XWPFDocument 对象 项目框架用的若依springboot vue
* 参数 title 为当前段落的文本,JSONArray为表格的内容
*JSONArray array = new JSONArray();
*JSONObject object = new JSONObject();
*object.put("question", bbQuestion.getBbQuestion());//问题
*object.put("type", bbQuestion.getBbType());//类型
*object.put("answer","是");//答案
*array.add(object);
*/
public class ExportWordUtil {
  
public static void exportManyWord(XWPFDocument doc, String title, JSONArray dataArray){
XWPFParagraph p = doc.createParagraph();// 新建一个段落
p.setAlignment(ParagraphAlignment.CENTER);
CTSpacing spacing = p.getCTP().addNewPPr().addNewSpacing();
spacing.setBefore(BigInteger.valueOf(4 * 240)); // 240 Twips = 1 磅 = 1/72 英寸
XWPFRun r = p.createRun();//创建段落文本
r.setText(title);
r.setBold(true);//设置为粗体
r.setText("\r");
// 行(9) 列
XWPFTable table = doc.createTable(9, 4);//创建一个表格
table.setWidth("100%");
mergeCellsInRow(0, 0, 1, table);
mergeCellsInRow(0, 2, 3, table);
mergeCellsInRow(1, 0, 1, table);
mergeCellsInRow(1, 2, 3, table);
mergeCellsInRow(2, 0, 1, table);
mergeCellsInRow(2, 2, 3, table);
mergeCellsInRow(3, 0, 1, table);
mergeCellsInRow(3, 2, 3, table);
mergeCellsInRow(4, 0, 3, table);
mergeCellsInRow(5, 0, 3, table);
mergeCellsInRow(6, 0, 3, table);
table.getRow(0).getCell(0).setText("填报日期");
table.getRow(0).getCell(0).setWidth("50%");
XWPFParagraph paragraph00 = table.getRow(0).getCell(0).getParagraphArray(0);
paragraph00.setAlignment(ParagraphAlignment.CENTER);
table.getRow(0).getCell(2).setText("配送商业");
table.getRow(0).getCell(2).setWidth("50%");
XWPFParagraph paragraph02 = table.getRow(0).getCell(2).getParagraphArray(0);
paragraph02.setAlignment(ParagraphAlignment.CENTER);

table.getRow(1).getCell(0).setText("");
table.getRow(1).getCell(0).setWidth("50%");
table.getRow(1).getCell(2).setText("");
table.getRow(1).getCell(2).setWidth("50%");

table.getRow(2).getCell(0).setText("产品名称");
table.getRow(2).getCell(0).setWidth("50%");
XWPFParagraph paragraph20 = table.getRow(2).getCell(0).getParagraphArray(0);
paragraph20.setAlignment(ParagraphAlignment.CENTER);
table.getRow(2).getCell(2).setText("规格");
table.getRow(2).getCell(2).setWidth("50%");
XWPFParagraph paragraph22 = table.getRow(2).getCell(2).getParagraphArray(0);
paragraph22.setAlignment(ParagraphAlignment.CENTER);
table.getRow(3).getCell(0).setText("");
table.getRow(3).getCell(0).setWidth("50%");
table.getRow(3).getCell(2).setText("");
table.getRow(3).getCell(2).setWidth("50%");
table.getRow(4).getCell(0).setWidth("100%");

XWPFTableCell cell4 = table.getRow(4).getCell(0);
//问卷内容
for (int i = 0; i < dataArray.size(); i++) {
JSONObject object = dataArray.getJSONObject(i);
cell4.setText("\r");
cell4.setText(" " + (i + 1)+ "、" + object.getString("question") + "\r");
if (object.getInteger("type") == 7){
XWPFParagraph paragraph = cell4.addParagraph();
XWPFRun run = paragraph.createRun();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(object.getString("answer").replace("/profile",""));
run.addPicture(fileInputStream,Document.PICTURE_TYPE_PNG, "TEST", Units.toEMU(200), Units.toEMU(100));
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
throw new RuntimeException(e);
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 2. 获取到图片数据
// CTDrawing drawing = run.getCTR().getDrawingArray(0);
// CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
// //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性
// CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "TEST1",
// Units.toEMU(100), Units.toEMU(30),//图片大小
// Units.toEMU(50), Units.toEMU(0), false);//相对当前段落位置 需要计算段落已有内容的左偏移
// drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性
// drawing.removeInline(0);//删除行内属性
} else {
cell4.setText("\r");
cell4.setText(" " + object.getString("answer"));
cell4.setText("\r");
}
}
table.getRow(5).getCell(0).setText("有何建议");
table.getRow(5).getCell(0).setWidth("100%");
XWPFTableCell cell = table.getRow(5).getCell(0);
cell.addParagraph();//换行
cell.addParagraph();
cell.addParagraph();
table.getRow(6).getCell(0).setText("(请根据实际情况勾选)");
table.getRow(6).getCell(0).setWidth("100%");
table.getRow(7).getCell(0).setText("填报地区:");
table.getRow(7).getCell(2).setText("填报时间:");
table.getRow(7).getCell(0).setWidth("25%");
table.getRow(7).getCell(1).setWidth("25%");
table.getRow(7).getCell(2).setWidth("25%");
table.getRow(7).getCell(3).setWidth("25%");
table.getRow(8).getCell(0).setText("受访人:");
table.getRow(8).getCell(2).setText("访问人:");
table.getRow(8).getCell(0).setWidth("25%");
table.getRow(8).getCell(1).setWidth("25%");
table.getRow(8).getCell(2).setWidth("25%");
table.getRow(8).getCell(3).setWidth("25%");
}
private static void mergeCellsInRow(int row, int fromCol, int toCol, XWPFTable table) {
for (int col = fromCol; col <= toCol; col++) {
table.getRow(row).getCell(col).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
if (col == fromCol) {
table.getRow(row).getCell(col).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
} else {
table.getRow(row).getCell(col).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
}
}
}

private static String convertFileToBase64(String filePath) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
byte[] fileBytes = new byte[fileInputStream.available()];
fileInputStream.read(fileBytes);
return Base64.getEncoder().encodeToString(fileBytes);
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* @param ctGraphicalObject 图片数据
* @param deskFileName 图片描述
* @param width 宽
* @param height 高
* @param leftOffset 水平偏移 left
* @param topOffset 垂直偏移 top
* @param behind 文字上方,文字下方
* @return
* @throws Exception
*/
public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject,
String deskFileName, int width, int height,
int leftOffset, int topOffset, boolean behind) {
String anchorXML =
"<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
+ "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"" + ((behind) ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
+ "<wp:simplePos x=\"0\" y=\"0\"/>"
+ "<wp:positionH relativeFrom=\"column\">"
+ "<wp:posOffset>" + leftOffset + "</wp:posOffset>"
+ "</wp:positionH>"
+ "<wp:positionV relativeFrom=\"paragraph\">"
+ "<wp:posOffset>" + topOffset + "</wp:posOffset>" +
"</wp:positionV>"
+ "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>"
+ "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
+ "<wp:wrapNone/>"
+ "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"" + deskFileName + "\"/><wp:cNvGraphicFramePr/>"
+ "</wp:anchor>";

CTDrawing drawing = null;
try {
drawing = CTDrawing.Factory.parse(anchorXML);
} catch (XmlException e) {
e.printStackTrace();
}
CTAnchor anchor = drawing.getAnchorArray(0);
anchor.setGraphic(ctGraphicalObject);
return anchor;
}
}

 

最后生成的结果,欢迎指正优化

标签:word,import,setText,getRow,文档,实操,getCell,table,setWidth
From: https://www.cnblogs.com/michaelcnblogs/p/18283752

相关文章

  • 从PDF到OFD,国产化浪潮下多种文档格式导出的完美解决方案
    最新技术资源(建议收藏)https://www.grapecity.com.cn/resources/前言近年来,中国在信息技术领域持续追求自主创新和供应链安全,伴随信创上升为国家战略,一些行业也开始明确要求文件导出的格式必须为OFD格式。OFD格式目前在政府、金融、税务、教育、医疗等需要文件开放、......
  • 哨兵1SAR空间数据包协议数据单元文档(六)
    《哨兵1SAR空间数据包协议数据单元》文档对数据包的结构进行了详细描述,并提供了用户数据的格式和解码算法。原文链接:哨兵1SAR空间数据包协议数据单元文档英文版同系列中的其他文章篇链接:哨兵1SAR空间数据包协议数据单元文档(一)哨兵1SAR空间数据包协议数据单元文......
  • 只需7个小时,利用ChatGPT撰写学术论文的最详细实操指南
    欢迎关注,为大家带来最酷最有效的智能AI学术科研写作攻略。关于使用ChatGPT等AI学术科研的相关问题可以和作者七哥yida985交流地表功能最强大的高级学术AI专业版已经开放,拥有全球领先的GPT学术科研应用,有兴趣的朋友可以联系获取试用,联系七哥获取学术AI使用教程。以下是一系列......
  • pdf的表格怎么转换成word?
    Adobe设计PDF文件格式的目的是支持跨平台、多媒体集成的信息出版和发布,特别是对网络信息发布的支持。为了实现这一目标,PDF具有许多其他电子文件格式无法比拟的优势。如今,越来越多的电子书籍、产品描述、公司通知、网络数据和电子邮件开始使用PDF格式文件。但是PDF却不能直接编辑,因......
  • python编写使用xmlrpc上传wordpress网站文章的程序
    1、安装库        pipinstallpython-wordpress-xmlrpc,tkinter,xmlrpc,json2、发布文章url="http://域名/xmlrpc.php"username=用户名password=密码title=标题content=内容tags=标签categories=分类client=C......
  • 最新AI大模型系统源码,ChatGPT商业运营版系统源(详细图文搭建部署教程)+AI绘画系统,DALL-E
    一、前言人工智能语言模型和AI绘画在多个领域都有广泛的应用.....SparkAi创作系统是一款基于ChatGPT和Midjourney开发的智能问答和绘画系统,提供一站式AIB/C端解决方案,涵盖AI大模型提问、AI绘画、文档分析、图像识别和理解、TTS&语音识别、AI换脸等多项功能。支持GPTs应......
  • Power BI进阶秘籍,干货满满!如何将度量值转化为切片器(动态切换分析指标),实操指南来了!
    PowerBI进阶秘籍,干货满满!如何将度量值转化为切片器(动态切换分析指标),实操指南来了! 想要在PowerBI中让度量值也能像维度一样灵活筛选?没问题,这里就为你揭秘如何将度量值转化为切片器(动态切换分析指标)的实用方法! 一、了解基础:首先,要知道PowerBI原生不支持直接将度量值作为切......
  • Spring Cloud Gateway整合Knife4j 4.4.0实现微服务聚合文档(报错解决详细版)
    以前做过的都是单服务应用的文档,就算换到了微服务里做的实际上也是单服务(每个服务模块一个单独的文档,然后手动访问不同的端口去查找不同的模块文档,例如用户是3000端口,订单是3100端口,商品是3200端口)。这样的实现实际上挺蠢的,对前端伙伴很不友好,对自己测试也不友好,因此今天要说的......
  • 最新AI源码-ChatGPT商业运营版系统源码,AI绘画网站系统,TTS & 语音识别对话、文档分析、
    一、前言人工智能语言模型和AI绘画在多个领域都有广泛的应用.....SparkAi创作系统是一款基于ChatGPT和Midjourney开发的智能问答和绘画系统,提供一站式AIB/C端解决方案,涵盖AI大模型提问、AI绘画、文档分析、图像识别和理解、TTS&语音识别、AI换脸等多项功能。支持GPTs应......
  • 外挂级OCR神器:免费文档解析、表格识别、手写识别、古籍识别、PDF转Word
    TextInTools是一款免费的在线OCR工具,支持快速准确的文字和表格识别,手写、古籍识别,提供PDF转Markdown大模型辅助工具,同时支持PDF、WORD、EXCEL、JPG、PPT等各类格式文件的转化。 TextInTools特点免费:所有产品提供每日200页免费额度,覆盖日常使用需求。方......