Apache POI用XWPFDocument操纵word,创建表格

1 篇文章 0 订阅
1 篇文章 0 订阅

领导将数据字典中生成word文档的功能交给了一位同事,他过来和我讨论。经过一番搜索找到了使用Apache POI这个开源框架的方法,不得不说这个框架真的非常的优秀,下面我将贴出我用来测试的代码(由于时间比较有限,就没有细致得整理代码),供以后参考使用。

1.pom依赖

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>4.0.0</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>4.0.0</version>
		</dependency>

2.java 代码

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xwpf.usermodel.TableWidthType;
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.XWPFTableRow;

public class Test {
	public static void main(String[] args) {
		// 文档生成方法
		XWPFDocument doc = new XWPFDocument();
		XWPFParagraph p1 = doc.createParagraph(); // 创建段落
		XWPFRun r1 = p1.createRun(); // 创建段落文本
		r1.setText("目录"); // 设置文本
		FileOutputStream out = null; // 创建输出流
		try {
			// 向word文档中添加内容
			XWPFParagraph p3 = doc.createParagraph(); // 创建段落
			XWPFRun r3 = p3.createRun(); // 创建段落文本
			r3.addTab();// tab
			r3.addBreak();// 换行
			r3.setBold(true);
			XWPFParagraph p2 = doc.createParagraph(); // 创建段落
			XWPFRun r2 = p2.createRun(); // 创建段落文本
			// 设置文本
			r2.setText("表名");
			r2.setFontSize(14);
			r2.setBold(true);
			XWPFTable table1 = doc.createTable(8, 10);
			table1.setWidthType(TableWidthType.AUTO);

			// 获取到刚刚插入的行
			XWPFTableRow row1 = table1.getRow(0);
			// 设置单元格内容
			row1.getCell(0).setText("字段名");
			row1.getCell(1).setText("字段说明");
			row1.getCell(2).setText("数据类型");
			row1.getCell(3).setText("长度");
			row1.getCell(4).setText("索引");
			row1.getCell(5).setText("是否为空");
			row1.getCell(6).setText("主键");
			row1.getCell(7).setText("外键");
			row1.getCell(8).setText("缺省值");
			row1.getCell(9).setText("备注");

			doc.setTable(0, table1);
			String filePath = "D:\\simple.docx";
			out = new FileOutputStream(new File(filePath));
			doc.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}

		}

	}
}

 

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值