java导出word
Java可以使用Apache POI库来导出Word文档。以下是一个简单的示例:
- 添加依赖
在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
- 编写代码
以下是一个简单的示例代码,用于创建一个包含“Hello World”文本的Word文档并将其保存到指定的文件路径:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class WordExporter {
public static void export(String filePath) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Hello World");
FileOutputStream out = new FileOutputStream(filePath);
document.write(out);
out.close();
document.close();
}
}
- 调用方法
可以在其他Java类中调用export方法来导出Word文档,例如:
public static void main(String[] args) {
try {
WordExporter.export("C:/Users/username/Desktop/hello.docx");
} catch (Exception e) {
e.printStackTrace();
}
}
该代码将在桌面上创建一个名为“hello.docx”的Word文档,其中包含“Hello World”文本。
原文地址: http://www.cveoy.top/t/topic/b0GR 著作权归作者所有。请勿转载和采集!