系列文章目录
五、Apache poi给excel单元格添加下拉框或数据验证
文章目录
一、介绍
本文介绍使用 Apache POI 操作Word文档(.docx)
引入依赖:
xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.3.0</version>
</dependency>
二、Apache POI中的常用方法
1.新建、读取、输出文档
1、新建
java
XWPFDocument document= new XWPFDocument();
2、读取
java
FileInputStream fileInputStream = new FileInputStream("D:/桌面/createdocument.docx");
XWPFDocument document= new XWPFDocument(fileInputStream);
3、输出
java
FileOutputStream out = new FileOutputStream("D:/桌面/createdocument.docx");
document.write(out);
document.close();
out.close();
2.段落
1、创建、写入段落
java
// 创建段落
XWPFParagraph paragraph = document.createParagraph();
// 运行段落
XWPFRun run = paragraph.createRun();
run.setText("北国风光,千里冰封,万里雪飘。\n" +
"望长城内外,惟余莽莽;大河上下,顿失滔滔。\n" +
"山舞银蛇,原驰蜡象,欲与天公试比高。\n" +
"须晴日,看红装素裹,分外妖娆。\n" +
"江山如此多娇,引无数英雄竞折腰。\n" +
"惜秦皇汉武,略输文采;唐宗宋祖,稍逊风骚。\n" +
"一代天骄,成吉思汗,只识弯弓射大雕。\n" +
"俱往矣,数风流人物,还看今朝。");
2、获取段落
java
XWPFParagraph paragraph = document.getParagraph(ctp); // 通过CTP获取段落
List<XWPFParagraph> paragraphs = document.getParagraphs(); // 获取段落集合
XWPFParagraph paragraphArray = document.getParagraphArray(1); // 段落索引获取段落
3、获取段落文本、修改内容
java
String text = paragraph.getText(); // 获取段落后获取段落文本
// 获取段落后删除run,创建新的run并设置文本内容。
List<XWPFParagraph> paragraphs = document.getParagraphs();
paragraphs.getFirst().removeRun(0);
paragraphs.getFirst().createRun().setText("test");
4、删除段落
java
boolean b = document.removeBodyElement(0); // 段落索引删除
// 通过段落内容删除
for (int i = 0; i < document.getParagraphs().size(); i++) {
XWPFParagraph paragraph = document.getParagraphs().get(i);
if (paragraph.getText().contains("想要删除的段落文本")) {
document.removeBodyElement(i);
break;
}
}
5、插入换行符
java
run.addBreak();
6、段落格式
java
// 设置段落对齐方式
paragraph1.setAlignment(ParagraphAlignment.LEFT);
// 设置段落缩进
paragraph1.setIndentationLeft(440); // 左缩进,单位为 twips(1 twip = 1/20 点)(字号 * 20 约为 缩进1字符)
paragraph1.setIndentationRight(440); // 右缩进
paragraph1.setIndentationFirstLine(440); // 首行缩进两字符
// 设置段落行间距
CTPPr pPr = paragraph1.getCTP().getPPr();
CTSpacing spacing = pPr.isSetSpacing() ? pPr.getSpacing() : pPr.addNewSpacing();
spacing.setAfter(BigInteger.valueOf(220)); // 段前间距,单位为 twips
spacing.setBefore(BigInteger.valueOf(220)); // 段后间距
spacing.setLine(BigInteger.valueOf(360)); // 行间距,单位为 twips
spacing.setLineRule(STLineSpacingRule.AUTO); // 行间距规则
// 设置段落间距
CTInd ind = pPr.isSetInd() ? pPr.getInd() : pPr.addNewInd();
ind.setLeft(BigInteger.valueOf(440)); // 左缩进
ind.setRight(BigInteger.valueOf(440)); // 右缩进
ind.setFirstLine(BigInteger.valueOf(440)); // 首行缩进
3.字体
java
run.setFontFamily("宋体"); // 设置字体名称
run.setFontSize(14); // 设置字体大小
run.setColor("FF0000"); // 设置字体颜色 红色
run.setBold(true); // 设置粗体
run.setItalic(true); // 设置斜体
run.setUnderline(UnderlinePatterns.SINGLE); // 设置下划线
run.setStrikeThrough(true); // 设置删除线
4.边框
java
paragraph.setBorderBottom(Borders.BASIC_BLACK_DASHES);
paragraph.setBorderLeft(Borders.BASIC_BLACK_DASHES);
paragraph.setBorderRight(Borders.BASIC_BLACK_DASHES);
paragraph.setBorderTop(Borders.BASIC_BLACK_DASHES);
5.表格
1、创建表格、填写内容
java
// 方式1
XWPFTable table = document.createTable(3, 3);
XWPFTableRow row = table.getRow(0); // 获取第一行
row.getCell(0).setText("Header 1"); // 设置单元格内容
row.getCell(1).setText("Header 2");
row.getCell(2).setText("Header 3");
XWPFTableRow newRow = table.createRow(); // 创建新的一行
newRow.getCell(0).setText("Data 1");
newRow.getCell(1).setText("Data 2");
newRow.getCell(2).setText("Data 3");
// 方式2
XWPFTable table = document.createTable();
// 第一行
XWPFTableRow tableRowOne = table.getRow(0);
tableRowOne.getCell(0).setText("col one, row one");
tableRowOne.addNewTableCell().setText("col two, row one");
tableRowOne.addNewTableCell().setText("col three, row one");
// 第二行
XWPFTableRow tableRowTwo = table.createRow();
tableRowTwo.getCell(0).setText("col one, row two");
tableRowTwo.getCell(1).setText("col two, row two");
tableRowTwo.getCell(2).setText("col three, row two");
// 第三行
XWPFTableRow tableRowThree = table.createRow();
tableRowThree.getCell(0).setText("col one, row three");
tableRowThree.getCell(1).setText("col two, row three");
tableRowThree.getCell(2).setText("col three, row three");
2、获取表格、修改内容
java
// 假设我们要修改第一个表格
XWPFTable tables = document.getTables().getFirst();
// 假设我们要修改第一行第二列的单元格(索引从0开始)
int rowIndex = 0;
int cellIndex = 1;
XWPFTableRow row = tables.getRow(rowIndex);
if (row != null) {
XWPFTableCell cell = row.getCell(cellIndex);
if (cell != null) {
// 清空单元格原有的所有段落
for (int i = cell.getParagraphs().size() - 1; i >= 0; i--) {
cell.removeParagraph(i);
}
// 添加新的段落到单元格
XWPFParagraph paragraph = cell.addParagraph();
XWPFRun run = paragraph.createRun();
run.setText("这是新的单元格内容----------");
}
}
3、设置表格行高、列宽
java
List<XWPFTableRow> rows = table.getRows();
List<XWPFTableCell> tableCells = rows.getFirst().getTableCells();
for (int i = 0; i < rows.size(); i++) {
table.getRow(i).setHeight(1000); // 设置行高
for (int j = 0; j < tableCells.size(); j++) {
table.getRow(i).getCell(j).setWidth("3000"); // 设置列宽 必要时做null判断
}
}
4、设置边框
java
// 设置外边框
table.setTopBorder(XWPFTable.XWPFBorderType.SINGLE, 20, 0, "006400"); // 线条样式 宽度 偏移 颜色
table.setBottomBorder(XWPFTable.XWPFBorderType.SINGLE, 20, 0, "006400");
table.setLeftBorder(XWPFTable.XWPFBorderType.SINGLE, 20, 0, "006400");
table.setRightBorder(XWPFTable.XWPFBorderType.SINGLE, 20, 0, "006400");
CTTblBorders borders = table.getCTTbl().getTblPr().addNewTblBorders();
// 设置内边框
CTBorder hBorder = borders.addNewInsideH();
hBorder.setVal(STBorder.Enum.forString("double"));
hBorder.setSz(new BigInteger("1")); // 线条大小
hBorder.setColor("191970"); // 设置颜色
CTBorder vBorder = borders.addNewInsideV();
vBorder.setVal(STBorder.Enum.forString("double"));
vBorder.setSz(new BigInteger("1"));
vBorder.setColor("191970");
5、设置背景色
java
CTShd shd = CTShd.Factory.newInstance();
shd.setFill("FF0000"); // 设置背景色为红色
cell.getCTTc().addNewTcPr().addNewShd().set(shd);
6、设置对齐方式
java
// 设置文本对齐方式
for (XWPFParagraph p : cell.getParagraphs()) {
p.setAlignment(ParagraphAlignment.CENTER); // 水平居中对齐
}
CTVerticalJc vjc = cell.getCTTc().addNewTcPr().addNewVAlign();
vjc.setVal(STVerticalJc.CENTER); // 垂直居中对齐
7、合并
java
mergeCellsHorizontally(table, 0, 0, 2); // 合并第1行第1列到第3列
mergeCellsVertically(table, 1, 0, 2); // 合并第2行第1列到第3行第1列
private static void mergeCellsHorizontally(XWPFTable table, int row, int fromCol, int toCol) {
for (int col = fromCol; col <= toCol; col++) {
XWPFTableCell cell = table.getRow(row).getCell(col);
if (col != fromCol) {
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
} else {
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
}
}
}
private static void mergeCellsVertically(XWPFTable table, int fromRow, int col, int toRow) {
for (int row = fromRow; row <= toRow; row++) {
XWPFTableCell cell = table.getRow(row).getCell(col);
if (row != fromRow) {
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
} else {
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
}
}
}
8、拆分
java
splitCellsHorizontally(table, 0, 0, 2); // 拆分第1行第1列到第4列
splitCellsVertically(table, 1, 0, 2); // 拆分第2行第1列到第3行第1列
private static void splitCellsHorizontally(XWPFTable table, int row, int fromCol, int toCol) {
for (int col = fromCol; col <= toCol; col++) {
XWPFTableCell cell = table.getRow(row).getCell(col);
if (col != fromCol) {
removeHMerge(cell);
}
}
}
private static void splitCellsVertically(XWPFTable table, int fromRow, int col, int toRow) {
for (int row = fromRow; row <= toRow; row++) {
XWPFTableCell cell = table.getRow(row).getCell(col);
if (row != fromRow) {
removeVMerge(cell);
}
}
}
private static void removeHMerge(XWPFTableCell cell) {
CTTcPr tcPr = cell.getCTTc().getTcPr();
if (tcPr != null) {
XmlCursor cursor = tcPr.newCursor();
while (cursor.hasNextToken()) {
if ("hMerge".equals(cursor.getName().getLocalPart())) {
cursor.removeXml();
break;
}
cursor.toNextToken();
}
cursor.dispose();
}
}
private static void removeVMerge(XWPFTableCell cell) {
CTTcPr tcPr = cell.getCTTc().getTcPr();
if (tcPr != null) {
XmlCursor cursor = tcPr.newCursor();
while (cursor.hasNextToken()) {
if ("vMerge".equals(cursor.getName().getLocalPart())) {
cursor.removeXml();
break;
}
cursor.toNextToken();
}
cursor.dispose();
}
}
6.图片
1、插入图片
java
// 插入图片
String imagePath = "D:/桌面/128c46f7fa08b0eb7b6c17f5f2bb9b1.jpg";
FileInputStream imageStream = new FileInputStream(imagePath);
int format = XWPFDocument.PICTURE_TYPE_JPEG;
// 创建段落
XWPFParagraph paragraph = document.createParagraph();
// 运行段落
XWPFRun run = paragraph.createRun();
// 插入图片到段落中
run.addPicture(imageStream, format, imagePath, Units.toEMU(200), Units.toEMU(200)); // 图片宽高为 200px