gradle依赖
implementation 'org.apache.poi:poi:3.17'
implementation 'org.apache.poi:poi-scratchpad:3.17'
implementation 'org.apache.poi:poi-ooxml:3.17'
implementation 'fr.opensagres.xdocreport:xdocreport:2.0.1'
implementation 'org.apache.poi:poi-ooxml-schemas:3.17'
implementation 'org.apache.poi:ooxml-schemas:1.4'
import fr.opensagres.poi.xwpf.converter.core.BasicURIResolver;
import fr.opensagres.poi.xwpf.converter.core.FileImageExtractor;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.*;
public class WordToHtmlUtils {
public static void main(String [] args) throws Exception {
String path = "C:\\Users\\x\\Desktop\\";
String wordName = "1.docx";
try {
wordToHTML(path+wordName,path);
System.out.println("转换成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void wordToHTML(String wordFile,String HTMLFile) throws Exception{
File file = new File(wordFile);
String wordName = file.getName();
String wordPath = file.getAbsolutePath().replace(wordName,"");
String htmlName = wordName.substring(0,wordName.lastIndexOf("."))+".html";
HTMLFile += htmlName;
File f = new File(HTMLFile);
InputStream in = new FileInputStream(wordFile);
InputStream result = docxToHtml(in,wordPath);
OutputStream outputStream = new FileOutputStream(f);
int byteWritten = 0;
int byteCount = 0;
byte[] bytes = new byte[1024];
while ((byteCount = result.read(bytes)) != -1){
outputStream.write(bytes,byteWritten,byteCount);
}
in.close();
result.close();
outputStream.close();
}
public static InputStream docxToHtml(InputStream in,String filePath){
XWPFDocument document = null;
try {
document = new XWPFDocument(in);
XHTMLOptions options = XHTMLOptions.create();
options.setIgnoreStylesIfUnused(false);
options.setFragment(true);
filePath = filePath+"image"+File.separator;
options.setExtractor(new FileImageExtractor(new File(filePath)));
options.URIResolver(new BasicURIResolver("image"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
XHTMLConverter.getInstance().convert(document,out,options);
return new ByteArrayInputStream(out.toByteArray());
}catch (IOException e){
}
return in;
}
}