免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
java如何打開word文檔_如何在Java中打開和操作Word文檔/模板?
userphoto

2022.10.31 湖南

關(guān)注

長不大的BEN

于 2021-02-24 10:01:54 發(fā)布

907

 收藏 1

文章標(biāo)簽: java如何打開word文檔

版權(quán)

我知道自從我發(fā)布這個問題以來已經(jīng)很長時間了,我說我會在完成后發(fā)布我的解決方案.

所以在這里.

我希望有一天它會幫助某人.

這是一個完整的工作類,您只需將它放在應(yīng)用程序中,并將TEMPLATE_DIRECTORY_ROOT目錄與.docx模板放在根目錄中.

用法很簡單.

您將占位符(鍵)放在.docx文件中,然后傳遞文件名和包含該文件的相應(yīng)鍵值對的Map.

請享用!

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.Closeable;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.URI;

import java.util.Deque;

import java.util.Enumeration;

import java.util.HashMap;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.Map;

import java.util.UUID;

import java.util.zip.ZipEntry;

import java.util.zip.ZipFile;

import java.util.zip.ZipOutputStream;

import javax.faces.context.ExternalContext;

import javax.faces.context.FacesContext;

import javax.servlet.http.HttpServletResponse;

public class DocxManipulator {

private static final String MAIN_DOCUMENT_PATH = "word/document.xml";

private static final String TEMPLATE_DIRECTORY_ROOT = "TEMPLATES_DIRECTORY/";

/* PUBLIC METHODS */

/**

* Generates .docx document from given template and the substitution data

*

* @param templateName

* Template data

* @param substitutionData

* Hash map with the set of key-value pairs that represent

* substitution data

* @return

*/

public static Boolean generateAndSendDocx(String templateName, Map substitutionData) {

String templateLocation = TEMPLATE_DIRECTORY_ROOT + templateName;

String userTempDir = UUID.randomUUID().toString();

userTempDir = TEMPLATE_DIRECTORY_ROOT + userTempDir + "/";

try {

// Unzip .docx file

unzip(new File(templateLocation), new File(userTempDir));

// Change data

changeData(new File(userTempDir + MAIN_DOCUMENT_PATH), substitutionData);

// Rezip .docx file

zip(new File(userTempDir), new File(userTempDir + templateName));

// Send HTTP response

sendDOCXResponse(new File(userTempDir + templateName), templateName);

// Clean temp data

deleteTempData(new File(userTempDir));

}

catch (IOException ioe) {

System.out.println(ioe.getMessage());

return false;

}

return true;

}

/* PRIVATE METHODS */

/**

* Unzipps specified ZIP file to specified directory

*

* @param zipfile

* Source ZIP file

* @param directory

* Destination directory

* @throws IOException

*/

private static void unzip(File zipfile, File directory) throws IOException {

ZipFile zfile = new ZipFile(zipfile);

Enumeration extends ZipEntry> entries = zfile.entries();

while (entries.hasMoreElements()) {

ZipEntry entry = entries.nextElement();

File file = new File(directory, entry.getName());

if (entry.isDirectory()) {

file.mkdirs();

}

else {

file.getParentFile().mkdirs();

InputStream in = zfile.getInputStream(entry);

try {

copy(in, file);

}

finally {

in.close();

}

}

}

}

/**

* Substitutes keys found in target file with corresponding data

*

* @param targetFile

* Target file

* @param substitutionData

* Map of key-value pairs of data

* @throws IOException

*/

@SuppressWarnings({ "unchecked", "rawtypes" })

private static void changeData(File targetFile, Map substitutionData) throws IOException{

BufferedReader br = null;

String docxTemplate = "";

try {

br = new BufferedReader(new InputStreamReader(new FileInputStream(targetFile), "UTF-8"));

String temp;

while( (temp = br.readLine()) != null)

docxTemplate = docxTemplate + temp;

br.close();

targetFile.delete();

}

catch (IOException e) {

br.close();

throw e;

}

Iterator substitutionDataIterator = substitutionData.entrySet().iterator();

while(substitutionDataIterator.hasNext()){

Map.Entry pair = (Map.Entry)substitutionDataIterator.next();

if(docxTemplate.contains(pair.getKey())){

if(pair.getValue() != null)

docxTemplate = docxTemplate.replace(pair.getKey(), pair.getValue());

else

docxTemplate = docxTemplate.replace(pair.getKey(), "NEDOSTAJE");

}

}

FileOutputStream fos = null;

try{

fos = new FileOutputStream(targetFile);

fos.write(docxTemplate.getBytes("UTF-8"));

fos.close();

}

catch (IOException e) {

fos.close();

throw e;

}

}

/**

* Zipps specified directory and all its subdirectories

*

* @param directory

* Specified directory

* @param zipfile

* Output ZIP file name

* @throws IOException

*/

private static void zip(File directory, File zipfile) throws IOException {

URI base = directory.toURI();

Deque queue = new LinkedList();

queue.push(directory);

OutputStream out = new FileOutputStream(zipfile);

Closeable res = out;

try {

ZipOutputStream zout = new ZipOutputStream(out);

res = zout;

while (!queue.isEmpty()) {

directory = queue.pop();

for (File kid : directory.listFiles()) {

String name = base.relativize(kid.toURI()).getPath();

if (kid.isDirectory()) {

queue.push(kid);

name = name.endsWith("/") ? name : name + "/";

zout.putNextEntry(new ZipEntry(name));

}

else {

if(kid.getName().contains(".docx"))

continue;

zout.putNextEntry(new ZipEntry(name));

copy(kid, zout);

zout.closeEntry();

}

}

}

}

finally {

res.close();

}

}

/**

* Sends HTTP Response containing .docx file to Client

*

* @param generatedFile

* Path to generated .docx file

* @param fileName

* File name of generated file that is being presented to user

* @throws IOException

*/

private static void sendDOCXResponse(File generatedFile, String fileName) throws IOException {

FacesContext facesContext = FacesContext.getCurrentInstance();

ExternalContext externalContext = facesContext.getExternalContext();

HttpServletResponse response = (HttpServletResponse) externalContext

.getResponse();

BufferedInputStream input = null;

BufferedOutputStream output = null;

response.reset();

response.setHeader("Content-Type", "application/msword");

response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

response.setHeader("Content-Length",String.valueOf(generatedFile.length()));

input = new BufferedInputStream(new FileInputStream(generatedFile), 10240);

output = new BufferedOutputStream(response.getOutputStream(), 10240);

byte[] buffer = new byte[10240];

for (int length; (length = input.read(buffer)) > 0;) {

output.write(buffer, 0, length);

}

output.flush();

input.close();

output.close();

// Inform JSF not to proceed with rest of life cycle

facesContext.responseComplete();

}

/**

* Deletes directory and all its subdirectories

*

* @param file

* Specified directory

* @throws IOException

*/

public static void deleteTempData(File file) throws IOException {

if (file.isDirectory()) {

// directory is empty, then delete it

if (file.list().length == 0)

file.delete();

else {

// list all the directory contents

String files[] = file.list();

for (String temp : files) {

// construct the file structure

File fileDelete = new File(file, temp);

// recursive delete

deleteTempData(fileDelete);

}

// check the directory again, if empty then delete it

if (file.list().length == 0)

file.delete();

}

} else {

// if file, then delete it

file.delete();

}

}

private static void copy(InputStream in, OutputStream out) throws IOException {

byte[] buffer = new byte[1024];

while (true) {

int readCount = in.read(buffer);

if (readCount < 0) {

break;

}

out.write(buffer, 0, readCount);

}

}

private static void copy(File file, OutputStream out) throws IOException {

InputStream in = new FileInputStream(file);

try {

copy(in, out);

} finally {

in.close();

}

}

private static void copy(InputStream in, File file) throws IOException {

OutputStream out = new FileOutputStream(file);

try {

copy(in, out);

} finally {

out.close();

}

}

}

————————————————

版權(quán)聲明:本文為CSDN博主「長不大的BEN」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。

原文鏈接:https://blog.csdn.net/weixin_42345187/article/details/114557185

本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
jar文件替換
回憶Java 之 文件讀寫及性能比較總結(jié)
java 創(chuàng)建文件夾以及文本文件
Java文件操作
java壓縮解壓代碼
[原創(chuàng)]JAVA讀取文件或是數(shù)據(jù)流的源代碼--涵蓋了多種形式
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服